DefaultTypeConverter.cs 13 KB

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