DefaultObjectConverter.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. }
  66. else
  67. {
  68. var t = value.GetType();
  69. if (!engine.Options.Interop.AllowSystemReflection
  70. && t.Namespace?.StartsWith("System.Reflection", StringComparison.Ordinal) == true)
  71. {
  72. const string Message = "Cannot access System.Reflection namespace, check Engine's interop options";
  73. ExceptionHelper.ThrowInvalidOperationException(Message);
  74. }
  75. if (t.IsEnum)
  76. {
  77. var ut = Enum.GetUnderlyingType(t);
  78. if (ut == typeof(ulong))
  79. {
  80. result = JsNumber.Create(Convert.ToDouble(value, CultureInfo.InvariantCulture));
  81. }
  82. else
  83. {
  84. if (ut == typeof(uint) || ut == typeof(long))
  85. {
  86. result = JsNumber.Create(Convert.ToInt64(value, CultureInfo.InvariantCulture));
  87. }
  88. else
  89. {
  90. result = JsNumber.Create(Convert.ToInt32(value, CultureInfo.InvariantCulture));
  91. }
  92. }
  93. }
  94. else
  95. {
  96. // check global cache, have we already wrapped the value?
  97. if (engine._objectWrapperCache?.TryGetValue(value, out var cached) == true)
  98. {
  99. result = cached;
  100. }
  101. else
  102. {
  103. var wrapped = engine.Options.Interop.WrapObjectHandler.Invoke(engine, value, type);
  104. if (ReferenceEquals(wrapped?.GetPrototypeOf(), engine.Realm.Intrinsics.Object.PrototypeObject)
  105. && engine._typeReferences?.TryGetValue(t, out var typeReference) == true)
  106. {
  107. wrapped.SetPrototypeOf(typeReference);
  108. }
  109. result = wrapped;
  110. if (engine.Options.Interop.TrackObjectWrapperIdentity && wrapped is not null)
  111. {
  112. engine._objectWrapperCache ??= new ConditionalWeakTable<object, ObjectInstance>();
  113. engine._objectWrapperCache.Add(value, wrapped);
  114. }
  115. }
  116. }
  117. // if no known type could be guessed, use the default of wrapping using using ObjectWrapper.
  118. }
  119. }
  120. return result is not null;
  121. }
  122. private static bool TryConvertConvertible(Engine engine, IConvertible convertible, [NotNullWhen(true)] out JsValue? result)
  123. {
  124. result = convertible.GetTypeCode() switch
  125. {
  126. TypeCode.Boolean => convertible.ToBoolean(engine.Options.Culture) ? JsBoolean.True : JsBoolean.False,
  127. TypeCode.Byte => JsNumber.Create(convertible.ToByte(engine.Options.Culture)),
  128. TypeCode.Char => JsString.Create(convertible.ToChar(engine.Options.Culture)),
  129. TypeCode.Double => JsNumber.Create(convertible.ToDouble(engine.Options.Culture)),
  130. TypeCode.SByte => JsNumber.Create(convertible.ToSByte(engine.Options.Culture)),
  131. TypeCode.Int16 => JsNumber.Create(convertible.ToInt16(engine.Options.Culture)),
  132. TypeCode.Int32 => JsNumber.Create(convertible.ToInt32(engine.Options.Culture)),
  133. TypeCode.UInt16 => JsNumber.Create(convertible.ToUInt16(engine.Options.Culture)),
  134. TypeCode.Int64 => JsNumber.Create(convertible.ToInt64(engine.Options.Culture)),
  135. TypeCode.Single => JsNumber.Create(convertible.ToSingle(engine.Options.Culture)),
  136. TypeCode.String => JsString.Create(convertible.ToString(engine.Options.Culture)),
  137. TypeCode.UInt32 => JsNumber.Create(convertible.ToUInt32(engine.Options.Culture)),
  138. TypeCode.UInt64 => JsNumber.Create(convertible.ToUInt64(engine.Options.Culture)),
  139. TypeCode.DateTime => engine.Realm.Intrinsics.Date.Construct(convertible.ToDateTime(engine.Options.Culture)),
  140. TypeCode.Decimal => JsNumber.Create(convertible.ToDecimal(engine.Options.Culture)),
  141. TypeCode.DBNull => JsValue.Null,
  142. TypeCode.Empty => JsValue.Null,
  143. _ => null
  144. };
  145. return result is not null;
  146. }
  147. private static JsArray ConvertArray(Engine e, object v)
  148. {
  149. var array = (Array) v;
  150. var arrayLength = (uint) array.Length;
  151. var values = new JsValue[arrayLength];
  152. for (uint i = 0; i < arrayLength; ++i)
  153. {
  154. values[i] = JsValue.FromObject(e, array.GetValue(i));
  155. }
  156. return new JsArray(e, values);
  157. }
  158. }
  159. }