DefaultTypeConverter.cs 11 KB

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