DefaultTypeConverter.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using Jint.Native;
  6. using System.Collections.Generic;
  7. using System.Reflection;
  8. namespace Jint.Runtime.Interop
  9. {
  10. public class DefaultTypeConverter : ITypeConverter
  11. {
  12. private readonly Engine _engine;
  13. private static readonly Dictionary<string, bool> _knownConversions = new Dictionary<string, bool>();
  14. private static readonly object _lockObject = new object();
  15. private static MethodInfo convertChangeType = typeof(System.Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type), typeof(IFormatProvider) } );
  16. private static MethodInfo jsValueFromObject = typeof(JsValue).GetMethod("FromObject");
  17. private static MethodInfo jsValueToObject = typeof(JsValue).GetMethod("ToObject");
  18. public DefaultTypeConverter(Engine engine)
  19. {
  20. _engine = engine;
  21. }
  22. public virtual object Convert(object value, Type type, IFormatProvider formatProvider)
  23. {
  24. if (value == null)
  25. {
  26. if (TypeConverter.TypeIsNullable(type))
  27. {
  28. return null;
  29. }
  30. throw new NotSupportedException(string.Format("Unable to convert null to '{0}'", type.FullName));
  31. }
  32. // don't try to convert if value is derived from type
  33. if (type.IsInstanceOfType(value))
  34. {
  35. return value;
  36. }
  37. if (type.IsEnum)
  38. {
  39. var integer = System.Convert.ChangeType(value, typeof(int), formatProvider);
  40. if (integer == null)
  41. {
  42. throw new ArgumentOutOfRangeException();
  43. }
  44. return Enum.ToObject(type, integer);
  45. }
  46. var valueType = value.GetType();
  47. // is the javascript value an ICallable instance ?
  48. if (valueType == typeof(Func<JsValue, JsValue[], JsValue>))
  49. {
  50. var function = (Func<JsValue, JsValue[], JsValue>)value;
  51. if (type.IsGenericType)
  52. {
  53. var genericType = type.GetGenericTypeDefinition();
  54. // create the requested Delegate
  55. if (genericType.Name.StartsWith("Action"))
  56. {
  57. var genericArguments = type.GetGenericArguments();
  58. var @params = new ParameterExpression[genericArguments.Count()];
  59. for (var i = 0; i < @params.Count(); i++)
  60. {
  61. @params[i] = Expression.Parameter(genericArguments[i], genericArguments[i].Name + i);
  62. }
  63. var @vars = Expression.NewArrayInit(typeof(JsValue), @params.Select(p => Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, typeof(Engine)), p)));
  64. var callExpresion = Expression.Block(Expression.Call(
  65. Expression.Call(Expression.Constant(function.Target),
  66. function.Method,
  67. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  68. @vars),
  69. jsValueToObject), Expression.Empty());
  70. return Expression.Lambda(callExpresion, new ReadOnlyCollection<ParameterExpression>(@params));
  71. }
  72. else if (genericType.Name.StartsWith("Func"))
  73. {
  74. var genericArguments = type.GetGenericArguments();
  75. var returnType = genericArguments.Last();
  76. var @params = new ParameterExpression[genericArguments.Count() - 1];
  77. for (var i = 0; i < @params.Count(); i++)
  78. {
  79. @params[i] = Expression.Parameter(genericArguments[i], genericArguments[i].Name + i);
  80. }
  81. var @vars =
  82. Expression.NewArrayInit(typeof(JsValue),
  83. @params.Select(p => {
  84. var boxingExpression = Expression.Convert(p, typeof(object));
  85. return Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, typeof(Engine)), boxingExpression);
  86. })
  87. );
  88. // the final result's type needs to be changed before casting,
  89. // for instance when a function returns a number (double) but C# expects an integer
  90. var callExpresion = Expression.Convert(
  91. Expression.Call(null,
  92. convertChangeType,
  93. Expression.Call(
  94. Expression.Call(Expression.Constant(function.Target),
  95. function.Method,
  96. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  97. @vars),
  98. jsValueToObject),
  99. Expression.Constant(returnType, typeof(Type)),
  100. Expression.Constant(System.Globalization.CultureInfo.InvariantCulture, typeof(IFormatProvider))
  101. ),
  102. returnType);
  103. return Expression.Lambda(callExpresion, new ReadOnlyCollection<ParameterExpression>(@params));
  104. }
  105. }
  106. else
  107. {
  108. if (type == typeof(Action))
  109. {
  110. return (Action)(() => function(JsValue.Undefined, new JsValue[0]));
  111. }
  112. else if (type.IsSubclassOf(typeof(System.MulticastDelegate)))
  113. {
  114. var method = type.GetMethod("Invoke");
  115. var arguments = method.GetParameters();
  116. var @params = new ParameterExpression[arguments.Count()];
  117. for (var i = 0; i < @params.Count(); i++)
  118. {
  119. @params[i] = Expression.Parameter(typeof(object), arguments[i].Name);
  120. }
  121. var @vars = Expression.NewArrayInit(typeof(JsValue), @params.Select(p => Expression.Call(null, typeof(JsValue).GetMethod("FromObject"), Expression.Constant(_engine, typeof(Engine)), p)));
  122. var callExpression = Expression.Block(
  123. Expression.Call(
  124. Expression.Call(Expression.Constant(function.Target),
  125. function.Method,
  126. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  127. @vars),
  128. typeof(JsValue).GetMethod("ToObject")),
  129. Expression.Empty());
  130. var dynamicExpression = Expression.Invoke(Expression.Lambda(callExpression, new ReadOnlyCollection<ParameterExpression>(@params)), new ReadOnlyCollection<ParameterExpression>(@params));
  131. return Expression.Lambda(type, dynamicExpression, new ReadOnlyCollection<ParameterExpression>(@params));
  132. }
  133. }
  134. }
  135. return System.Convert.ChangeType(value, type, formatProvider);
  136. }
  137. public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
  138. {
  139. bool canConvert;
  140. var key = value == null ? String.Format("Null->{0}", type) : String.Format("{0}->{1}", value.GetType(), type);
  141. lock (_lockObject)
  142. {
  143. if (!_knownConversions.TryGetValue(key, out canConvert))
  144. {
  145. try
  146. {
  147. converted = Convert(value, type, formatProvider);
  148. _knownConversions.Add(key, true);
  149. return true;
  150. }
  151. catch
  152. {
  153. converted = null;
  154. _knownConversions.Add(key, false);
  155. return false;
  156. }
  157. }
  158. }
  159. if (canConvert)
  160. {
  161. converted = Convert(value, type, formatProvider);
  162. return true;
  163. }
  164. converted = null;
  165. return false;
  166. }
  167. }
  168. }