DefaultTypeConverter.cs 13 KB

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