DefaultTypeConverter.cs 14 KB

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