DefaultTypeConverter.cs 11 KB

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