ObjectWrapper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 type = Target.GetType();
  151. var key = new Engine.ClrPropertyDescriptorFactoriesKey(type, property.ToString());
  152. if (!_engine.ClrPropertyDescriptorFactories.TryGetValue(key, out var factory))
  153. {
  154. factory = ResolveProperty(type, property.ToString());
  155. _engine.ClrPropertyDescriptorFactories[key] = factory;
  156. }
  157. var descriptor = factory(_engine, Target);
  158. AddProperty(property, descriptor);
  159. return descriptor;
  160. }
  161. private Func<Engine, object, PropertyDescriptor> ResolveProperty(Type type, string propertyName)
  162. {
  163. var isNumber = uint.TryParse(propertyName, out _);
  164. // properties and fields cannot be numbers
  165. if (!isNumber)
  166. {
  167. // look for a property
  168. PropertyInfo property = null;
  169. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  170. {
  171. if (EqualsIgnoreCasing(p.Name, propertyName))
  172. {
  173. property = p;
  174. break;
  175. }
  176. }
  177. if (property != null)
  178. {
  179. return (engine, target) => new PropertyInfoDescriptor(engine, property, target);
  180. }
  181. // look for a field
  182. FieldInfo field = null;
  183. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  184. {
  185. if (EqualsIgnoreCasing(f.Name, propertyName))
  186. {
  187. field = f;
  188. break;
  189. }
  190. }
  191. if (field != null)
  192. {
  193. return (engine, target) => new FieldInfoDescriptor(engine, field, target);
  194. }
  195. // if no properties were found then look for a method
  196. List<MethodInfo> methods = null;
  197. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  198. {
  199. if (EqualsIgnoreCasing(m.Name, propertyName))
  200. {
  201. methods ??= new List<MethodInfo>();
  202. methods.Add(m);
  203. }
  204. }
  205. if (methods?.Count > 0)
  206. {
  207. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, methods.ToArray()), PropertyFlag.OnlyEnumerable);
  208. }
  209. }
  210. // if no methods are found check if target implemented indexing
  211. if (IndexDescriptor.TryFindIndexer(_engine, type, propertyName, out _, out _, out _))
  212. {
  213. return (engine, target) => new IndexDescriptor(engine, propertyName, target);
  214. }
  215. // try to find a single explicit property implementation
  216. List<PropertyInfo> list = null;
  217. foreach (Type iface in type.GetInterfaces())
  218. {
  219. foreach (var iprop in iface.GetProperties())
  220. {
  221. if (EqualsIgnoreCasing(iprop.Name, propertyName))
  222. {
  223. list ??= new List<PropertyInfo>();
  224. list.Add(iprop);
  225. }
  226. }
  227. }
  228. if (list?.Count == 1)
  229. {
  230. return (engine, target) => new PropertyInfoDescriptor(engine, list[0], target);
  231. }
  232. // try to find explicit method implementations
  233. List<MethodInfo> explicitMethods = null;
  234. foreach (Type iface in type.GetInterfaces())
  235. {
  236. foreach (var imethod in iface.GetMethods())
  237. {
  238. if (EqualsIgnoreCasing(imethod.Name, propertyName))
  239. {
  240. explicitMethods ??= new List<MethodInfo>();
  241. explicitMethods.Add(imethod);
  242. }
  243. }
  244. }
  245. if (explicitMethods?.Count > 0)
  246. {
  247. return (engine, target) => new PropertyDescriptor(new MethodInfoFunctionInstance(engine, explicitMethods.ToArray()), PropertyFlag.OnlyEnumerable);
  248. }
  249. // try to find explicit indexer implementations
  250. foreach (Type interfaceType in type.GetInterfaces())
  251. {
  252. if (IndexDescriptor.TryFindIndexer(_engine, interfaceType, propertyName, out _, out _, out _))
  253. {
  254. return (engine, target) => new IndexDescriptor(engine, interfaceType, propertyName, target);
  255. }
  256. }
  257. return (engine, target) => PropertyDescriptor.Undefined;
  258. }
  259. private static bool EqualsIgnoreCasing(string s1, string s2)
  260. {
  261. bool equals = false;
  262. if (s1.Length == s2.Length)
  263. {
  264. if (s1.Length > 0)
  265. {
  266. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  267. }
  268. if (equals && s1.Length > 1)
  269. {
  270. equals = s1.Substring(1) == s2.Substring(1);
  271. }
  272. }
  273. return equals;
  274. }
  275. }
  276. }