DefaultTypeConverter.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 tmpVars = new Expression[@params.Length];
  64. for (var i = 0; i < @params.Count(); i++)
  65. {
  66. var param = @params[i];
  67. if (param.Type.IsValueType)
  68. {
  69. var boxing = Expression.Convert(param, typeof(object));
  70. tmpVars[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, typeof(Engine)), boxing);
  71. }
  72. else
  73. {
  74. tmpVars[i] = Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, typeof(Engine)), param);
  75. }
  76. }
  77. var @vars = Expression.NewArrayInit(typeof(JsValue), tmpVars);
  78. var callExpresion = Expression.Block(Expression.Call(
  79. Expression.Call(Expression.Constant(function.Target),
  80. function.Method,
  81. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  82. @vars),
  83. jsValueToObject), Expression.Empty());
  84. return Expression.Lambda(callExpresion, new ReadOnlyCollection<ParameterExpression>(@params)).Compile();
  85. }
  86. else if (genericType.Name.StartsWith("Func"))
  87. {
  88. var genericArguments = type.GetGenericArguments();
  89. var returnType = genericArguments.Last();
  90. var @params = new ParameterExpression[genericArguments.Count() - 1];
  91. for (var i = 0; i < @params.Count(); i++)
  92. {
  93. @params[i] = Expression.Parameter(genericArguments[i], genericArguments[i].Name + i);
  94. }
  95. var @vars =
  96. Expression.NewArrayInit(typeof(JsValue),
  97. @params.Select(p => {
  98. var boxingExpression = Expression.Convert(p, typeof(object));
  99. return Expression.Call(null, jsValueFromObject, Expression.Constant(_engine, typeof(Engine)), boxingExpression);
  100. })
  101. );
  102. // the final result's type needs to be changed before casting,
  103. // for instance when a function returns a number (double) but C# expects an integer
  104. var callExpresion = Expression.Convert(
  105. Expression.Call(null,
  106. convertChangeType,
  107. Expression.Call(
  108. Expression.Call(Expression.Constant(function.Target),
  109. function.Method,
  110. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  111. @vars),
  112. jsValueToObject),
  113. Expression.Constant(returnType, typeof(Type)),
  114. Expression.Constant(System.Globalization.CultureInfo.InvariantCulture, typeof(IFormatProvider))
  115. ),
  116. returnType);
  117. return Expression.Lambda(callExpresion, new ReadOnlyCollection<ParameterExpression>(@params)).Compile();
  118. }
  119. }
  120. else
  121. {
  122. if (type == typeof(Action))
  123. {
  124. return (Action)(() => function(JsValue.Undefined, new JsValue[0]));
  125. }
  126. else if (type.IsSubclassOf(typeof(System.MulticastDelegate)))
  127. {
  128. var method = type.GetMethod("Invoke");
  129. var arguments = method.GetParameters();
  130. var @params = new ParameterExpression[arguments.Count()];
  131. for (var i = 0; i < @params.Count(); i++)
  132. {
  133. @params[i] = Expression.Parameter(typeof(object), arguments[i].Name);
  134. }
  135. var @vars = Expression.NewArrayInit(typeof(JsValue), @params.Select(p => Expression.Call(null, typeof(JsValue).GetMethod("FromObject"), Expression.Constant(_engine, typeof(Engine)), p)));
  136. var callExpression = Expression.Block(
  137. Expression.Call(
  138. Expression.Call(Expression.Constant(function.Target),
  139. function.Method,
  140. Expression.Constant(JsValue.Undefined, typeof(JsValue)),
  141. @vars),
  142. typeof(JsValue).GetMethod("ToObject")),
  143. Expression.Empty());
  144. var dynamicExpression = Expression.Invoke(Expression.Lambda(callExpression, new ReadOnlyCollection<ParameterExpression>(@params)), new ReadOnlyCollection<ParameterExpression>(@params));
  145. return Expression.Lambda(type, dynamicExpression, new ReadOnlyCollection<ParameterExpression>(@params)).Compile();
  146. }
  147. }
  148. }
  149. if (type.IsArray)
  150. {
  151. var source = value as object[];
  152. if (source == null)
  153. throw new ArgumentException(String.Format("Value of object[] type is expected, but actual type is {0}.", value.GetType()));
  154. var targetElementType = type.GetElementType();
  155. var itemsConverted = source.Select(o => Convert(o, targetElementType, formatProvider)).ToArray();
  156. var result = Array.CreateInstance(targetElementType, source.Length);
  157. itemsConverted.CopyTo(result, 0);
  158. return result;
  159. }
  160. if (type.IsGenericType && type.GetGenericTypeDefinition()==typeof(Nullable<>))
  161. type = Nullable.GetUnderlyingType(type);
  162. return System.Convert.ChangeType(value, type, formatProvider);
  163. }
  164. public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
  165. {
  166. bool canConvert;
  167. var key = value == null ? String.Format("Null->{0}", type) : String.Format("{0}->{1}", value.GetType(), type);
  168. if (!_knownConversions.TryGetValue(key, out canConvert))
  169. {
  170. lock (_lockObject)
  171. {
  172. if (!_knownConversions.TryGetValue(key, out canConvert))
  173. {
  174. try
  175. {
  176. converted = Convert(value, type, formatProvider);
  177. _knownConversions.Add(key, true);
  178. return true;
  179. }
  180. catch
  181. {
  182. converted = null;
  183. _knownConversions.Add(key, false);
  184. return false;
  185. }
  186. }
  187. }
  188. }
  189. if (canConvert)
  190. {
  191. converted = Convert(value, type, formatProvider);
  192. return true;
  193. }
  194. converted = null;
  195. return false;
  196. }
  197. }
  198. }