DefaultTypeConverter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // reference types - return null if no valid constructor is found
  115. if (!type.IsValueType)
  116. {
  117. var found = false;
  118. foreach (var constructor in constructors)
  119. {
  120. if (constructor.GetParameters().Length == 0 && constructor.IsPublic)
  121. {
  122. found = true;
  123. break;
  124. }
  125. }
  126. if (!found)
  127. {
  128. ExceptionHelper.ThrowArgumentException("No valid constructors found");
  129. }
  130. }
  131. var obj = Activator.CreateInstance(type, System.Array.Empty<object>());
  132. var members = type.GetMembers();
  133. foreach (var member in members)
  134. {
  135. // only use fields an properties
  136. if (member.MemberType != MemberTypes.Property &&
  137. member.MemberType != MemberTypes.Field)
  138. {
  139. continue;
  140. }
  141. var name = member.Name.UpperToLowerCamelCase();
  142. if (typeDescriptor.TryGetValue(value, name, out var val))
  143. {
  144. var output = Convert(val, member.GetDefinedType(), formatProvider);
  145. member.SetValue(obj, output);
  146. }
  147. }
  148. return obj;
  149. }
  150. try
  151. {
  152. return System.Convert.ChangeType(value, type, formatProvider);
  153. }
  154. catch (Exception e)
  155. {
  156. // check if we can do a cast with operator overloading
  157. if (TryCastWithOperators(value, type, valueType, out var invoke))
  158. {
  159. return invoke;
  160. }
  161. if (!_engine.Options.Interop.ExceptionHandler(e))
  162. {
  163. throw;
  164. }
  165. ExceptionHelper.ThrowError(_engine, e.Message);
  166. return null;
  167. }
  168. }
  169. private Delegate BuildDelegate(Type type, Func<JsValue, JsValue[], JsValue> function)
  170. {
  171. var method = type.GetMethod("Invoke");
  172. var arguments = method.GetParameters();
  173. var parameters = new ParameterExpression[arguments.Length];
  174. for (var i = 0; i < parameters.Length; i++)
  175. {
  176. parameters[i] = Expression.Parameter(arguments[i].ParameterType, arguments[i].Name);
  177. }
  178. var initializers = new MethodCallExpression[parameters.Length];
  179. for (var i = 0; i < parameters.Length; i++)
  180. {
  181. var param = parameters[i];
  182. if (param.Type.IsValueType)
  183. {
  184. var boxing = Expression.Convert(param, objectType);
  185. initializers[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, engineType), boxing);
  186. }
  187. else
  188. {
  189. initializers[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, engineType), param);
  190. }
  191. }
  192. var vars = Expression.NewArrayInit(jsValueType, initializers);
  193. var callExpression = Expression.Call(
  194. Expression.Constant(function.Target),
  195. function.Method,
  196. Expression.Constant(JsValue.Undefined, jsValueType),
  197. vars);
  198. if (method.ReturnType != typeof(void))
  199. {
  200. return Expression.Lambda(
  201. type,
  202. Expression.Convert(
  203. Expression.Call(
  204. null,
  205. convertChangeType,
  206. Expression.Call(callExpression, jsValueToObject),
  207. Expression.Constant(method.ReturnType),
  208. Expression.Constant(System.Globalization.CultureInfo.InvariantCulture, typeof(IFormatProvider))
  209. ),
  210. method.ReturnType
  211. ),
  212. new ReadOnlyCollection<ParameterExpression>(parameters)).Compile();
  213. }
  214. return Expression.Lambda(
  215. type,
  216. callExpression,
  217. new ReadOnlyCollection<ParameterExpression>(parameters)).Compile();
  218. }
  219. private static bool TryCastWithOperators(object value, Type type, Type valueType, [NotNullWhen(true)] out object? converted)
  220. {
  221. var key = new TypeConversionKey(valueType, type);
  222. static MethodInfo? CreateValueFactory(TypeConversionKey k)
  223. {
  224. var (source, target) = k;
  225. foreach (var m in source.GetOperatorOverloadMethods().Concat(target.GetOperatorOverloadMethods()))
  226. {
  227. if (!target.IsAssignableFrom(m.ReturnType) || m.Name is not ("op_Implicit" or "op_Explicit"))
  228. {
  229. continue;
  230. }
  231. var parameters = m.GetParameters();
  232. if (parameters.Length != 1 || !parameters[0].ParameterType.IsAssignableFrom(source))
  233. {
  234. continue;
  235. }
  236. // we found a match
  237. return m;
  238. }
  239. return null;
  240. }
  241. var castOperator = _knownCastOperators.GetOrAdd(key, CreateValueFactory);
  242. if (castOperator != null)
  243. {
  244. try
  245. {
  246. converted = castOperator.Invoke(null, new[] { value });
  247. return true;
  248. }
  249. catch
  250. {
  251. converted = null;
  252. return false;
  253. }
  254. }
  255. converted = null;
  256. return false;
  257. }
  258. public virtual bool TryConvert(object? value, Type type, IFormatProvider formatProvider, out object? converted)
  259. {
  260. var key = new TypeConversionKey(value?.GetType() ?? typeof(void), type);
  261. // string conversion is not stable, "filter" -> int is invalid, "0" -> int is valid
  262. var canConvert = value is string || _knownConversions.GetOrAdd(key, _ =>
  263. {
  264. try
  265. {
  266. Convert(value, type, formatProvider);
  267. return true;
  268. }
  269. catch
  270. {
  271. return false;
  272. }
  273. });
  274. if (canConvert)
  275. {
  276. try
  277. {
  278. converted = Convert(value, type, formatProvider);
  279. return true;
  280. }
  281. catch
  282. {
  283. converted = null;
  284. return false;
  285. }
  286. }
  287. converted = null;
  288. return false;
  289. }
  290. }
  291. internal static class ObjectExtensions
  292. {
  293. public static object? GetHiddenClrObjectProperty(this ObjectInstance obj, string name)
  294. {
  295. return (obj.Get(name) as IObjectWrapper)?.Target;
  296. }
  297. public static void SetHiddenClrObjectProperty(this ObjectInstance obj, string name, object value)
  298. {
  299. obj.SetOwnProperty(name, new PropertyDescriptor(new ObjectWrapper(obj.Engine, value), PropertyFlag.AllForbidden));
  300. }
  301. }
  302. }