ObjectWrapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 (Target is IDictionary dictionary && includeStrings)
  128. {
  129. // we take values exposed as dictionary keys only
  130. foreach (var key in dictionary.Keys)
  131. {
  132. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  133. {
  134. var jsString = JsString.Create((string) stringKey);
  135. processed?.Add(jsString);
  136. yield return jsString;
  137. }
  138. }
  139. }
  140. else if (includeStrings)
  141. {
  142. // we take public properties and fields
  143. var type = Target.GetType();
  144. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  145. {
  146. var indexParameters = p.GetIndexParameters();
  147. if (indexParameters.Length == 0)
  148. {
  149. var jsString = JsString.Create(p.Name);
  150. processed?.Add(jsString);
  151. yield return jsString;
  152. }
  153. }
  154. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  155. {
  156. var jsString = JsString.Create(f.Name);
  157. processed?.Add(jsString);
  158. yield return jsString;
  159. }
  160. }
  161. if (processed != null)
  162. {
  163. // we have base keys
  164. for (var i = 0; i < basePropertyKeys.Count; i++)
  165. {
  166. var key = basePropertyKeys[i];
  167. if (processed.Add(key))
  168. {
  169. yield return key;
  170. }
  171. }
  172. }
  173. }
  174. public override PropertyDescriptor GetOwnProperty(JsValue property)
  175. {
  176. if (TryGetProperty(property, out var x))
  177. {
  178. return x;
  179. }
  180. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  181. {
  182. var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", (thisObject, arguments) => _engine.Iterator.Construct(this), 1, PropertyFlag.Configurable);
  183. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  184. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  185. return iteratorProperty;
  186. }
  187. var member = property.ToString();
  188. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  189. if (result is not null)
  190. {
  191. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  192. }
  193. var accessor = GetAccessor(_engine, Target.GetType(), member);
  194. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
  195. SetProperty(member, descriptor);
  196. return descriptor;
  197. }
  198. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  199. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  200. {
  201. // fast path which uses slow search if not found for some reason
  202. ReflectionAccessor Factory()
  203. {
  204. return member switch
  205. {
  206. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  207. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  208. FieldInfo fi => new FieldAccessor(fi),
  209. _ => null
  210. };
  211. }
  212. return GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  213. }
  214. private static ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func<ReflectionAccessor> accessorFactory = null)
  215. {
  216. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  217. var factories = Engine.ReflectionAccessors;
  218. if (factories.TryGetValue(key, out var accessor))
  219. {
  220. return accessor;
  221. }
  222. accessor = accessorFactory?.Invoke() ?? ResolvePropertyDescriptorFactory(engine, type, member);
  223. // racy, we don't care, worst case we'll catch up later
  224. Interlocked.CompareExchange(ref Engine.ReflectionAccessors,
  225. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  226. {
  227. [key] = accessor
  228. }, factories);
  229. return accessor;
  230. }
  231. private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine, Type type, string memberName)
  232. {
  233. if (typeof(DynamicObject).IsAssignableFrom(type))
  234. {
  235. return new DynamicObjectAccessor(typeof(void), memberName);
  236. }
  237. var isNumber = uint.TryParse(memberName, out _);
  238. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  239. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  240. // properties and fields cannot be numbers
  241. if (!isNumber && TryFindStringPropertyAccessor(type, memberName, indexer, out var temp))
  242. {
  243. return temp;
  244. }
  245. // if no methods are found check if target implemented indexing
  246. if (indexerAccessor != null)
  247. {
  248. return indexerAccessor;
  249. }
  250. // try to find a single explicit property implementation
  251. List<PropertyInfo> list = null;
  252. foreach (Type iface in type.GetInterfaces())
  253. {
  254. foreach (var iprop in iface.GetProperties())
  255. {
  256. if (EqualsIgnoreCasing(iprop.Name, memberName))
  257. {
  258. list ??= new List<PropertyInfo>();
  259. list.Add(iprop);
  260. }
  261. }
  262. }
  263. if (list?.Count == 1)
  264. {
  265. return new PropertyAccessor(memberName, list[0]);
  266. }
  267. // try to find explicit method implementations
  268. List<MethodInfo> explicitMethods = null;
  269. foreach (Type iface in type.GetInterfaces())
  270. {
  271. foreach (var imethod in iface.GetMethods())
  272. {
  273. if (EqualsIgnoreCasing(imethod.Name, memberName))
  274. {
  275. explicitMethods ??= new List<MethodInfo>();
  276. explicitMethods.Add(imethod);
  277. }
  278. }
  279. }
  280. if (explicitMethods?.Count > 0)
  281. {
  282. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  283. }
  284. // try to find explicit indexer implementations
  285. foreach (var interfaceType in type.GetInterfaces())
  286. {
  287. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  288. {
  289. return accessor;
  290. }
  291. }
  292. if (engine.Options._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  293. {
  294. var matches = new List<MethodInfo>();
  295. foreach (var method in extensionMethods)
  296. {
  297. if (EqualsIgnoreCasing(method.Name, memberName))
  298. {
  299. matches.Add(method);
  300. }
  301. }
  302. return new MethodAccessor(MethodDescriptor.Build(matches));
  303. }
  304. return ConstantValueAccessor.NullAccessor;
  305. }
  306. private static bool TryFindStringPropertyAccessor(
  307. Type type,
  308. string memberName,
  309. PropertyInfo indexerToTry,
  310. out ReflectionAccessor wrapper)
  311. {
  312. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  313. PropertyInfo property = null;
  314. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  315. {
  316. // only if it's not an indexer, we can do case-ignoring matches
  317. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  318. if (!isStandardIndexer && EqualsIgnoreCasing(p.Name, memberName))
  319. {
  320. property = p;
  321. break;
  322. }
  323. }
  324. if (property != null)
  325. {
  326. wrapper = new PropertyAccessor(memberName, property, indexerToTry);
  327. return true;
  328. }
  329. // look for a field
  330. FieldInfo field = null;
  331. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  332. {
  333. if (EqualsIgnoreCasing(f.Name, memberName))
  334. {
  335. field = f;
  336. break;
  337. }
  338. }
  339. if (field != null)
  340. {
  341. wrapper = new FieldAccessor(field, memberName, indexerToTry);
  342. return true;
  343. }
  344. // if no properties were found then look for a method
  345. List<MethodInfo> methods = null;
  346. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  347. {
  348. if (EqualsIgnoreCasing(m.Name, memberName))
  349. {
  350. methods ??= new List<MethodInfo>();
  351. methods.Add(m);
  352. }
  353. }
  354. if (methods?.Count > 0)
  355. {
  356. wrapper = new MethodAccessor(MethodDescriptor.Build(methods));
  357. return true;
  358. }
  359. wrapper = default;
  360. return false;
  361. }
  362. private static bool EqualsIgnoreCasing(string s1, string s2)
  363. {
  364. if (s1.Length != s2.Length)
  365. {
  366. return false;
  367. }
  368. var equals = false;
  369. if (s1.Length > 0)
  370. {
  371. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  372. }
  373. if (@equals && s1.Length > 1)
  374. {
  375. #if NETSTANDARD2_1
  376. equals = s1.AsSpan(1).SequenceEqual(s2.AsSpan(1));
  377. #else
  378. equals = s1.Substring(1) == s2.Substring(1);
  379. #endif
  380. }
  381. return equals;
  382. }
  383. }
  384. }