DefaultObjectConverter.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. using System.Runtime.CompilerServices;
  4. using System.Threading;
  5. using Jint.Native;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Interop;
  9. namespace Jint
  10. {
  11. internal static class DefaultObjectConverter
  12. {
  13. private static Dictionary<Type, Func<Engine, object, JsValue>> _typeMappers = new()
  14. {
  15. { typeof(bool), (engine, v) => (bool)v ? JsBoolean.True : JsBoolean.False },
  16. { typeof(byte), (engine, v) => JsNumber.Create((byte)v) },
  17. { typeof(char), (engine, v) => JsString.Create((char)v) },
  18. { typeof(DateTime), (engine, v) => engine.Realm.Intrinsics.Date.Construct((DateTime)v) },
  19. { typeof(DateTimeOffset), (engine, v) => engine.Realm.Intrinsics.Date.Construct((DateTimeOffset)v) },
  20. { typeof(decimal), (engine, v) => (JsValue)(double)(decimal)v },
  21. { typeof(double), (engine, v) => (JsValue)(double)v },
  22. { typeof(short), (engine, v) => JsNumber.Create((short)v) },
  23. { typeof(int), (engine, v) => JsNumber.Create((int)v) },
  24. { typeof(long), (engine, v) => (JsValue)(long)v },
  25. { typeof(sbyte), (engine, v) => JsNumber.Create((sbyte)v) },
  26. { typeof(float), (engine, v) => (JsValue)(float)v },
  27. { typeof(string), (engine, v) => JsString.Create((string)v) },
  28. { typeof(ushort), (engine, v) => JsNumber.Create((ushort)v) },
  29. { typeof(uint), (engine, v) => JsNumber.Create((uint)v) },
  30. { typeof(ulong), (engine, v) => JsNumber.Create((ulong)v) },
  31. {
  32. typeof(System.Text.RegularExpressions.Regex),
  33. (engine, v) => engine.Realm.Intrinsics.RegExp.Construct((System.Text.RegularExpressions.Regex)v, ((System.Text.RegularExpressions.Regex)v).ToString(), "")
  34. }
  35. };
  36. public static bool TryConvert(Engine engine, object value, Type? type, [NotNullWhen(true)] out JsValue? result)
  37. {
  38. result = null;
  39. Type valueType = ObjectWrapper.GetClrType(value, type);
  40. var typeMappers = _typeMappers;
  41. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  42. {
  43. result = typeMapper(engine, value);
  44. }
  45. else
  46. {
  47. if (value is Array a)
  48. {
  49. // racy, we don't care, worst case we'll catch up later
  50. Interlocked.CompareExchange(ref _typeMappers,
  51. new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  52. {
  53. [valueType] = ConvertArray
  54. }, typeMappers);
  55. result = ConvertArray(engine, a);
  56. return result is not null;
  57. }
  58. if (value is IConvertible convertible && TryConvertConvertible(engine, convertible, out result))
  59. {
  60. return true;
  61. }
  62. if (value is Delegate d)
  63. {
  64. result = new DelegateWrapper(engine, d);
  65. return result is not null;
  66. }
  67. if (value is Task task)
  68. {
  69. result = JsValue.ConvertAwaitableToPromise(engine, task);
  70. return result is not null;
  71. }
  72. #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
  73. if (value is ValueTask valueTask)
  74. {
  75. result = JsValue.ConvertAwaitableToPromise(engine, valueTask);
  76. return result is not null;
  77. }
  78. #endif
  79. var t = value.GetType();
  80. if (!engine.Options.Interop.AllowSystemReflection
  81. && t.Namespace?.StartsWith("System.Reflection", StringComparison.Ordinal) == true)
  82. {
  83. const string Message = "Cannot access System.Reflection namespace, check Engine's interop options";
  84. ExceptionHelper.ThrowInvalidOperationException(Message);
  85. }
  86. if (t.IsEnum)
  87. {
  88. var ut = Enum.GetUnderlyingType(t);
  89. if (ut == typeof(ulong))
  90. {
  91. result = JsNumber.Create(Convert.ToDouble(value, CultureInfo.InvariantCulture));
  92. }
  93. else
  94. {
  95. if (ut == typeof(uint) || ut == typeof(long))
  96. {
  97. result = JsNumber.Create(Convert.ToInt64(value, CultureInfo.InvariantCulture));
  98. }
  99. else
  100. {
  101. result = JsNumber.Create(Convert.ToInt32(value, CultureInfo.InvariantCulture));
  102. }
  103. }
  104. }
  105. else
  106. {
  107. // check global cache, have we already wrapped the value?
  108. if (engine._objectWrapperCache?.TryGetValue(value, out var cached) == true)
  109. {
  110. result = cached;
  111. }
  112. else
  113. {
  114. var wrapped = engine.Options.Interop.WrapObjectHandler.Invoke(engine, value, type);
  115. if (ReferenceEquals(wrapped?.GetPrototypeOf(), engine.Realm.Intrinsics.Object.PrototypeObject)
  116. && engine._typeReferences?.TryGetValue(t, out var typeReference) == true)
  117. {
  118. wrapped.SetPrototypeOf(typeReference);
  119. }
  120. result = wrapped;
  121. if (engine.Options.Interop.TrackObjectWrapperIdentity && wrapped is not null)
  122. {
  123. engine._objectWrapperCache ??= new ConditionalWeakTable<object, ObjectInstance>();
  124. engine._objectWrapperCache.Add(value, wrapped);
  125. }
  126. }
  127. }
  128. // if no known type could be guessed, use the default of wrapping using using ObjectWrapper.
  129. }
  130. return result is not null;
  131. }
  132. private static bool TryConvertConvertible(Engine engine, IConvertible convertible, [NotNullWhen(true)] out JsValue? result)
  133. {
  134. result = convertible.GetTypeCode() switch
  135. {
  136. TypeCode.Boolean => convertible.ToBoolean(engine.Options.Culture) ? JsBoolean.True : JsBoolean.False,
  137. TypeCode.Byte => JsNumber.Create(convertible.ToByte(engine.Options.Culture)),
  138. TypeCode.Char => JsString.Create(convertible.ToChar(engine.Options.Culture)),
  139. TypeCode.Double => JsNumber.Create(convertible.ToDouble(engine.Options.Culture)),
  140. TypeCode.SByte => JsNumber.Create(convertible.ToSByte(engine.Options.Culture)),
  141. TypeCode.Int16 => JsNumber.Create(convertible.ToInt16(engine.Options.Culture)),
  142. TypeCode.Int32 => JsNumber.Create(convertible.ToInt32(engine.Options.Culture)),
  143. TypeCode.UInt16 => JsNumber.Create(convertible.ToUInt16(engine.Options.Culture)),
  144. TypeCode.Int64 => JsNumber.Create(convertible.ToInt64(engine.Options.Culture)),
  145. TypeCode.Single => JsNumber.Create(convertible.ToSingle(engine.Options.Culture)),
  146. TypeCode.String => JsString.Create(convertible.ToString(engine.Options.Culture)),
  147. TypeCode.UInt32 => JsNumber.Create(convertible.ToUInt32(engine.Options.Culture)),
  148. TypeCode.UInt64 => JsNumber.Create(convertible.ToUInt64(engine.Options.Culture)),
  149. TypeCode.DateTime => engine.Realm.Intrinsics.Date.Construct(convertible.ToDateTime(engine.Options.Culture)),
  150. TypeCode.Decimal => JsNumber.Create(convertible.ToDecimal(engine.Options.Culture)),
  151. TypeCode.DBNull => JsValue.Null,
  152. TypeCode.Empty => JsValue.Null,
  153. _ => null
  154. };
  155. return result is not null;
  156. }
  157. private static JsArray ConvertArray(Engine e, object v)
  158. {
  159. var array = (Array) v;
  160. var arrayLength = (uint) array.Length;
  161. var values = new JsValue[arrayLength];
  162. for (uint i = 0; i < arrayLength; ++i)
  163. {
  164. values[i] = JsValue.FromObject(e, array.GetValue(i));
  165. }
  166. return new JsArray(e, values);
  167. }
  168. }
  169. }