DefaultObjectConverter.cs 8.1 KB

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