DefaultTypeConverter.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Dynamic;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using Jint.Extensions;
  10. using Jint.Native;
  11. namespace Jint.Runtime.Interop
  12. {
  13. public class DefaultTypeConverter : ITypeConverter
  14. {
  15. private readonly Engine _engine;
  16. #if NETSTANDARD
  17. private static readonly ConcurrentDictionary<(Type Source, Type Target), bool> _knownConversions = new ConcurrentDictionary<(Type Source, Type Target), bool>();
  18. private static readonly ConcurrentDictionary<(Type Source, Type Target), MethodInfo> _knownCastOperators = new ConcurrentDictionary<(Type Source, Type Target), MethodInfo>();
  19. #else
  20. private static readonly ConcurrentDictionary<string, bool> _knownConversions = new ConcurrentDictionary<string, bool>();
  21. private static readonly ConcurrentDictionary<string, MethodInfo> _knownCastOperators = new ConcurrentDictionary<string, MethodInfo>();
  22. #endif
  23. private static readonly Type intType = typeof(int);
  24. private static readonly Type iCallableType = typeof(Func<JsValue, JsValue[], JsValue>);
  25. private static readonly Type jsValueType = typeof(JsValue);
  26. private static readonly Type objectType = typeof(object);
  27. private static readonly Type engineType = typeof(Engine);
  28. private static readonly Type typeType = typeof(Type);
  29. private static readonly MethodInfo convertChangeType = typeof(Convert).GetMethod("ChangeType", new[] { objectType, typeType, typeof(IFormatProvider) });
  30. private static readonly MethodInfo jsValueFromObject = jsValueType.GetMethod(nameof(JsValue.FromObject));
  31. private static readonly MethodInfo jsValueToObject = jsValueType.GetMethod(nameof(JsValue.ToObject));
  32. public DefaultTypeConverter(Engine engine)
  33. {
  34. _engine = engine;
  35. }
  36. public virtual object Convert(object value, Type type, IFormatProvider formatProvider)
  37. {
  38. if (value == null)
  39. {
  40. if (TypeConverter.TypeIsNullable(type))
  41. {
  42. return null;
  43. }
  44. ExceptionHelper.ThrowNotSupportedException($"Unable to convert null to '{type.FullName}'");
  45. }
  46. // don't try to convert if value is derived from type
  47. if (type.IsInstanceOfType(value))
  48. {
  49. return value;
  50. }
  51. if (type.IsNullable())
  52. {
  53. type = Nullable.GetUnderlyingType(type);
  54. }
  55. if (type.IsEnum)
  56. {
  57. var integer = System.Convert.ChangeType(value, intType, formatProvider);
  58. if (integer == null)
  59. {
  60. ExceptionHelper.ThrowArgumentOutOfRangeException();
  61. }
  62. return Enum.ToObject(type, integer);
  63. }
  64. var valueType = value.GetType();
  65. // is the javascript value an ICallable instance ?
  66. if (valueType == iCallableType)
  67. {
  68. var function = (Func<JsValue, JsValue[], JsValue>) value;
  69. if (typeof(Delegate).IsAssignableFrom(type) && !type.IsAbstract)
  70. {
  71. var method = type.GetMethod("Invoke");
  72. var arguments = method.GetParameters();
  73. var @params = new ParameterExpression[arguments.Length];
  74. for (var i = 0; i < @params.Length; i++)
  75. {
  76. @params[i] = Expression.Parameter(arguments[i].ParameterType, arguments[i].Name);
  77. }
  78. var initializers = new MethodCallExpression[@params.Length];
  79. for (int i = 0; i < @params.Length; i++)
  80. {
  81. var param = @params[i];
  82. if (param.Type.IsValueType)
  83. {
  84. var boxing = Expression.Convert(param, objectType);
  85. initializers[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, engineType), boxing);
  86. }
  87. else
  88. {
  89. initializers[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, engineType), param);
  90. }
  91. }
  92. var @vars = Expression.NewArrayInit(jsValueType, initializers);
  93. var callExpression = Expression.Call(
  94. Expression.Constant(function.Target),
  95. function.Method,
  96. Expression.Constant(JsValue.Undefined, jsValueType),
  97. @vars);
  98. if (method.ReturnType != typeof(void))
  99. {
  100. return Expression.Lambda(
  101. type,
  102. Expression.Convert(
  103. Expression.Call(
  104. null,
  105. convertChangeType,
  106. Expression.Call(callExpression, jsValueToObject),
  107. Expression.Constant(method.ReturnType),
  108. Expression.Constant(System.Globalization.CultureInfo.InvariantCulture, typeof(IFormatProvider))
  109. ),
  110. method.ReturnType
  111. ),
  112. new ReadOnlyCollection<ParameterExpression>(@params)).Compile();
  113. }
  114. else
  115. {
  116. return Expression.Lambda(
  117. type,
  118. callExpression,
  119. new ReadOnlyCollection<ParameterExpression>(@params)).Compile();
  120. }
  121. }
  122. }
  123. if (type.IsArray)
  124. {
  125. var source = value as object[];
  126. if (source == null)
  127. {
  128. ExceptionHelper.ThrowArgumentException($"Value of object[] type is expected, but actual type is {value.GetType()}.");
  129. }
  130. var targetElementType = type.GetElementType();
  131. var itemsConverted = new object[source.Length];
  132. for (int i = 0; i < source.Length; i++)
  133. {
  134. itemsConverted[i] = Convert(source[i], targetElementType, formatProvider);
  135. }
  136. var result = Array.CreateInstance(targetElementType, source.Length);
  137. itemsConverted.CopyTo(result, 0);
  138. return result;
  139. }
  140. if (value is ExpandoObject eObj)
  141. {
  142. // public empty constructor required
  143. var constructors = type.GetConstructors();
  144. // value types
  145. if (type.IsValueType && constructors.Length > 0)
  146. {
  147. ExceptionHelper.ThrowArgumentException("No valid constructors found");
  148. }
  149. // reference types - return null if no valid constructor is found
  150. if (!type.IsValueType)
  151. {
  152. var found = false;
  153. foreach (var constructor in constructors)
  154. {
  155. if (constructor.GetParameters().Length == 0 && constructor.IsPublic)
  156. {
  157. found = true;
  158. break;
  159. }
  160. }
  161. if (!found)
  162. {
  163. ExceptionHelper.ThrowArgumentException("No valid constructors found");
  164. }
  165. }
  166. var dict = (IDictionary<string, object>) eObj;
  167. var obj = Activator.CreateInstance(type, System.Array.Empty<object>());
  168. var members = type.GetMembers();
  169. foreach (var member in members)
  170. {
  171. // only use fields an properties
  172. if (member.MemberType != MemberTypes.Property &&
  173. member.MemberType != MemberTypes.Field)
  174. {
  175. continue;
  176. }
  177. var name = member.Name.UpperToLowerCamelCase();
  178. if (dict.TryGetValue(name, out var val))
  179. {
  180. var output = Convert(val, member.GetDefinedType(), formatProvider);
  181. member.SetValue(obj, output);
  182. }
  183. }
  184. return obj;
  185. }
  186. if (_engine.Options.Interop.OperatorOverloadingAllowed)
  187. {
  188. #if NETSTANDARD
  189. var key = (valueType, type);
  190. #else
  191. var key = $"{valueType}->{type}";
  192. #endif
  193. var castOperator = _knownCastOperators.GetOrAdd(key, _ =>
  194. valueType.GetOperatorOverloadMethods()
  195. .Concat(type.GetOperatorOverloadMethods())
  196. .FirstOrDefault(m => type.IsAssignableFrom(m.ReturnType)
  197. && (m.Name == "op_Implicit" || m.Name == "op_Explicit")));
  198. if (castOperator != null)
  199. {
  200. return castOperator.Invoke(null, new[] { value });
  201. }
  202. }
  203. try
  204. {
  205. return System.Convert.ChangeType(value, type, formatProvider);
  206. }
  207. catch (Exception e)
  208. {
  209. if (!_engine.Options.Interop.ExceptionHandler(e))
  210. {
  211. throw;
  212. }
  213. ExceptionHelper.ThrowError(_engine, e.Message);
  214. return null;
  215. }
  216. }
  217. public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
  218. {
  219. #if NETSTANDARD
  220. var key = value == null ? (null, type) : (value.GetType(), type);
  221. #else
  222. var key = value == null ? $"Null->{type}" : $"{value.GetType()}->{type}";
  223. #endif
  224. // string conversion is not stable, "filter" -> int is invalid, "0" -> int is valid
  225. var canConvert = value is string || _knownConversions.GetOrAdd(key, _ =>
  226. {
  227. try
  228. {
  229. Convert(value, type, formatProvider);
  230. return true;
  231. }
  232. catch
  233. {
  234. return false;
  235. }
  236. });
  237. if (canConvert)
  238. {
  239. try
  240. {
  241. converted = Convert(value, type, formatProvider);
  242. return true;
  243. }
  244. catch
  245. {
  246. converted = null;
  247. return false;
  248. }
  249. }
  250. converted = null;
  251. return false;
  252. }
  253. }
  254. }