ObjectWrapper.cs 12 KB

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