ObjectWrapper.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. var propertyKeys = base.GetOwnPropertyKeys(types);
  76. if (Target is IDictionary dictionary)
  77. {
  78. // we take values exposed as dictionary keys only
  79. foreach (var key in dictionary.Keys)
  80. {
  81. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  82. {
  83. propertyKeys.Add(JsString.Create((string) stringKey));
  84. }
  85. }
  86. }
  87. else
  88. {
  89. // we take public properties and fields
  90. var type = Target.GetType();
  91. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  92. {
  93. var indexParameters = p.GetIndexParameters();
  94. if (indexParameters.Length == 0)
  95. {
  96. propertyKeys.Add(p.Name);
  97. }
  98. }
  99. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  100. {
  101. propertyKeys.Add(f.Name);
  102. }
  103. }
  104. return propertyKeys;
  105. }
  106. public override PropertyDescriptor GetOwnProperty(JsValue property)
  107. {
  108. if (TryGetProperty(property, out var x))
  109. {
  110. return x;
  111. }
  112. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  113. {
  114. var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", (thisObject, arguments) => _engine.Iterator.Construct(this), 1, PropertyFlag.Configurable);
  115. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  116. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  117. return iteratorProperty;
  118. }
  119. var type = Target.GetType();
  120. var key = new Engine.ClrPropertyDescriptorFactoriesKey(type, property.ToString());
  121. if (!_engine.ClrPropertyDescriptorFactories.TryGetValue(key, out var factory))
  122. {
  123. factory = ResolveProperty(type, property.ToString());
  124. _engine.ClrPropertyDescriptorFactories[key] = factory;
  125. }
  126. var descriptor = factory(_engine, Target);
  127. AddProperty(property, descriptor);
  128. return descriptor;
  129. }
  130. private Func<Engine, object, PropertyDescriptor> ResolveProperty(Type type, string propertyName)
  131. {
  132. var isNumber = uint.TryParse(propertyName, out _);
  133. // properties and fields cannot be numbers
  134. if (!isNumber)
  135. {
  136. // look for a property
  137. PropertyInfo property = null;
  138. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  139. {
  140. if (EqualsIgnoreCasing(p.Name, propertyName))
  141. {
  142. property = p;
  143. break;
  144. }
  145. }
  146. if (property != null)
  147. {
  148. return (engine, target) => new PropertyInfoDescriptor(engine, property, target);
  149. }
  150. // look for a field
  151. FieldInfo field = null;
  152. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  153. {
  154. if (EqualsIgnoreCasing(f.Name, propertyName))
  155. {
  156. field = f;
  157. break;
  158. }
  159. }
  160. if (field != null)
  161. {
  162. return (engine, target) => new FieldInfoDescriptor(engine, field, target);
  163. }
  164. // if no properties were found then look for a method
  165. List<MethodInfo> methods = null;
  166. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  167. {
  168. if (EqualsIgnoreCasing(m.Name, propertyName))
  169. {
  170. methods ??= new List<MethodInfo>();
  171. methods.Add(m);
  172. }
  173. }
  174. if (methods?.Count > 0)
  175. {
  176. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, methods.ToArray()), PropertyFlag.OnlyEnumerable);
  177. }
  178. }
  179. // if no methods are found check if target implemented indexing
  180. if (IndexDescriptor.TryFindIndexer(_engine, type, propertyName, out _, out _, out _))
  181. {
  182. return (engine, target) => new IndexDescriptor(engine, propertyName, target);
  183. }
  184. // try to find a single explicit property implementation
  185. List<PropertyInfo> list = null;
  186. foreach (Type iface in type.GetInterfaces())
  187. {
  188. foreach (var iprop in iface.GetProperties())
  189. {
  190. if (EqualsIgnoreCasing(iprop.Name, propertyName))
  191. {
  192. list ??= new List<PropertyInfo>();
  193. list.Add(iprop);
  194. }
  195. }
  196. }
  197. if (list?.Count == 1)
  198. {
  199. return (engine, target) => new PropertyInfoDescriptor(engine, list[0], target);
  200. }
  201. // try to find explicit method implementations
  202. List<MethodInfo> explicitMethods = null;
  203. foreach (Type iface in type.GetInterfaces())
  204. {
  205. foreach (var imethod in iface.GetMethods())
  206. {
  207. if (EqualsIgnoreCasing(imethod.Name, propertyName))
  208. {
  209. explicitMethods ??= new List<MethodInfo>();
  210. explicitMethods.Add(imethod);
  211. }
  212. }
  213. }
  214. if (explicitMethods?.Count > 0)
  215. {
  216. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, explicitMethods.ToArray()), PropertyFlag.OnlyEnumerable);
  217. }
  218. // try to find explicit indexer implementations
  219. foreach (Type interfaceType in type.GetInterfaces())
  220. {
  221. if (IndexDescriptor.TryFindIndexer(_engine, interfaceType, propertyName, out _, out _, out _))
  222. {
  223. return (engine, target) => new IndexDescriptor(engine, interfaceType, propertyName, target);
  224. }
  225. }
  226. return (engine, target) => PropertyDescriptor.Undefined;
  227. }
  228. private static bool EqualsIgnoreCasing(string s1, string s2)
  229. {
  230. bool equals = false;
  231. if (s1.Length == s2.Length)
  232. {
  233. if (s1.Length > 0)
  234. {
  235. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  236. }
  237. if (equals && s1.Length > 1)
  238. {
  239. equals = s1.Substring(1) == s2.Substring(1);
  240. }
  241. }
  242. return equals;
  243. }
  244. }
  245. }