DefaultTypeConverter.cs 12 KB

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