ObjectWrapper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.Descriptors.Specialized;
  11. namespace Jint.Runtime.Interop
  12. {
  13. /// <summary>
  14. /// Wraps a CLR instance
  15. /// </summary>
  16. public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper
  17. {
  18. public ObjectWrapper(Engine engine, object obj)
  19. : base(engine)
  20. {
  21. Target = obj;
  22. var type = obj.GetType();
  23. if (ObjectIsArrayLikeClrCollection(type))
  24. {
  25. // create a forwarder to produce length from Count or Length if one of them is present
  26. var lengthProperty = type.GetProperty("Count") ?? type.GetProperty("Length");
  27. if (lengthProperty is null)
  28. {
  29. return;
  30. }
  31. IsArrayLike = true;
  32. IsIntegerIndexedArray = typeof(IList).IsAssignableFrom(type);
  33. var functionInstance = new ClrFunctionInstance(engine, "length", (thisObj, arguments) => JsNumber.Create((int) lengthProperty.GetValue(obj)));
  34. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  35. SetProperty(KnownKeys.Length, descriptor);
  36. }
  37. }
  38. private static bool ObjectIsArrayLikeClrCollection(Type type)
  39. {
  40. if (typeof(ICollection).IsAssignableFrom(type))
  41. {
  42. return true;
  43. }
  44. foreach (var interfaceType in type.GetInterfaces())
  45. {
  46. if (!interfaceType.IsGenericType)
  47. {
  48. continue;
  49. }
  50. if (interfaceType.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>)
  51. || interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>))
  52. {
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. public object Target { get; }
  59. public override bool IsArrayLike { get; }
  60. internal override bool IsIntegerIndexedArray { get; }
  61. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  62. {
  63. if (!CanPut(property))
  64. {
  65. return false;
  66. }
  67. var ownDesc = GetOwnProperty(property);
  68. if (ownDesc == null)
  69. {
  70. return false;
  71. }
  72. ownDesc.Value = value;
  73. return true;
  74. }
  75. public override JsValue Get(JsValue property, JsValue receiver)
  76. {
  77. if (property.IsSymbol())
  78. {
  79. // wrapped objects cannot have symbol properties
  80. return Undefined;
  81. }
  82. if (property.IsInteger() && Target is IList list)
  83. {
  84. var index = (int) ((JsNumber) property)._value;
  85. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  86. }
  87. return base.Get(property, receiver);
  88. }
  89. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  90. {
  91. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  92. }
  93. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  94. {
  95. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  96. {
  97. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  98. }
  99. }
  100. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  101. {
  102. var basePropertyKeys = base.GetOwnPropertyKeys(types);
  103. // prefer object order, add possible other properties after
  104. var processed = basePropertyKeys.Count > 0 ? new HashSet<JsValue>() : null;
  105. var includeStrings = (types & Types.String) != 0;
  106. if (Target is IDictionary dictionary && includeStrings)
  107. {
  108. // we take values exposed as dictionary keys only
  109. foreach (var key in dictionary.Keys)
  110. {
  111. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  112. {
  113. var jsString = JsString.Create((string) stringKey);
  114. processed?.Add(jsString);
  115. yield return jsString;
  116. }
  117. }
  118. }
  119. else if (includeStrings)
  120. {
  121. // we take public properties and fields
  122. var type = Target.GetType();
  123. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  124. {
  125. var indexParameters = p.GetIndexParameters();
  126. if (indexParameters.Length == 0)
  127. {
  128. var jsString = JsString.Create(p.Name);
  129. processed?.Add(jsString);
  130. yield return jsString;
  131. }
  132. }
  133. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  134. {
  135. var jsString = JsString.Create(f.Name);
  136. processed?.Add(jsString);
  137. yield return jsString;
  138. }
  139. }
  140. if (processed != null)
  141. {
  142. // we have base keys
  143. for (var i = 0; i < basePropertyKeys.Count; i++)
  144. {
  145. var key = basePropertyKeys[i];
  146. if (processed.Add(key))
  147. {
  148. yield return key;
  149. }
  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 (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  160. {
  161. var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", (thisObject, arguments) => _engine.Iterator.Construct(this), 1, PropertyFlag.Configurable);
  162. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  163. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  164. return iteratorProperty;
  165. }
  166. var memberAccessor = Engine.Options._MemberAccessor;
  167. if (memberAccessor != null)
  168. {
  169. var result = memberAccessor.Invoke(Engine, Target, property.ToString());
  170. if (result != null)
  171. {
  172. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  173. }
  174. }
  175. var type = Target.GetType();
  176. var key = new ClrPropertyDescriptorFactoriesKey(type, property.ToString());
  177. if (!_engine.ClrPropertyDescriptorFactories.TryGetValue(key, out var factory))
  178. {
  179. factory = ResolveProperty(type, property.ToString());
  180. _engine.ClrPropertyDescriptorFactories[key] = factory;
  181. }
  182. var descriptor = factory(_engine, Target);
  183. AddProperty(property, descriptor);
  184. return descriptor;
  185. }
  186. private Func<Engine, object, PropertyDescriptor> ResolveProperty(Type type, string propertyName)
  187. {
  188. var isNumber = uint.TryParse(propertyName, out _);
  189. // properties and fields cannot be numbers
  190. if (!isNumber)
  191. {
  192. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  193. PropertyInfo property = null;
  194. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  195. {
  196. // only if it's not an indexer, we can do case-ignoring matches
  197. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  198. if (!isStandardIndexer && EqualsIgnoreCasing(p.Name, propertyName))
  199. {
  200. property = p;
  201. break;
  202. }
  203. }
  204. if (property != null)
  205. {
  206. return (engine, target) => new PropertyInfoDescriptor(engine, property, target);
  207. }
  208. // look for a field
  209. FieldInfo field = null;
  210. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  211. {
  212. if (EqualsIgnoreCasing(f.Name, propertyName))
  213. {
  214. field = f;
  215. break;
  216. }
  217. }
  218. if (field != null)
  219. {
  220. return (engine, target) => new FieldInfoDescriptor(engine, field, target);
  221. }
  222. // if no properties were found then look for a method
  223. List<MethodInfo> methods = null;
  224. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  225. {
  226. if (EqualsIgnoreCasing(m.Name, propertyName))
  227. {
  228. methods ??= new List<MethodInfo>();
  229. methods.Add(m);
  230. }
  231. }
  232. if (methods?.Count > 0)
  233. {
  234. var array = methods.ToArray();
  235. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, array), PropertyFlag.OnlyEnumerable);
  236. }
  237. }
  238. // if no methods are found check if target implemented indexing
  239. if (IndexDescriptor.TryFindIndexer(_engine, type, propertyName, out var indexerFactory))
  240. {
  241. return (engine, target) => indexerFactory(target);
  242. }
  243. // try to find a single explicit property implementation
  244. List<PropertyInfo> list = null;
  245. foreach (Type iface in type.GetInterfaces())
  246. {
  247. foreach (var iprop in iface.GetProperties())
  248. {
  249. if (EqualsIgnoreCasing(iprop.Name, propertyName))
  250. {
  251. list ??= new List<PropertyInfo>();
  252. list.Add(iprop);
  253. }
  254. }
  255. }
  256. if (list?.Count == 1)
  257. {
  258. return (engine, target) => new PropertyInfoDescriptor(engine, list[0], target);
  259. }
  260. // try to find explicit method implementations
  261. List<MethodInfo> explicitMethods = null;
  262. foreach (Type iface in type.GetInterfaces())
  263. {
  264. foreach (var imethod in iface.GetMethods())
  265. {
  266. if (EqualsIgnoreCasing(imethod.Name, propertyName))
  267. {
  268. explicitMethods ??= new List<MethodInfo>();
  269. explicitMethods.Add(imethod);
  270. }
  271. }
  272. }
  273. if (explicitMethods?.Count > 0)
  274. {
  275. var array = explicitMethods.ToArray();
  276. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, array), PropertyFlag.OnlyEnumerable);
  277. }
  278. // try to find explicit indexer implementations
  279. foreach (var interfaceType in type.GetInterfaces())
  280. {
  281. if (IndexDescriptor.TryFindIndexer(_engine, interfaceType, propertyName, out var interfaceIndexerFactory))
  282. {
  283. return (engine, target) => interfaceIndexerFactory(target);
  284. }
  285. }
  286. return (engine, target) => PropertyDescriptor.Undefined;
  287. }
  288. private static bool EqualsIgnoreCasing(string s1, string s2)
  289. {
  290. bool equals = false;
  291. if (s1.Length == s2.Length)
  292. {
  293. if (s1.Length > 0)
  294. {
  295. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  296. }
  297. if (equals && s1.Length > 1)
  298. {
  299. equals = s1.Substring(1) == s2.Substring(1);
  300. }
  301. }
  302. return equals;
  303. }
  304. }
  305. }