JsValue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.Contracts;
  5. using System.Runtime.CompilerServices;
  6. using System.Threading;
  7. using Jint.Native.Array;
  8. using Jint.Native.Date;
  9. using Jint.Native.Object;
  10. using Jint.Native.RegExp;
  11. using Jint.Runtime;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Interop;
  14. namespace Jint.Native
  15. {
  16. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  17. public abstract class JsValue : IEquatable<JsValue>
  18. {
  19. public static readonly JsValue Undefined = new JsUndefined();
  20. public static readonly JsValue Null = new JsNull();
  21. internal readonly Types _type;
  22. protected JsValue(Types type)
  23. {
  24. _type = type;
  25. }
  26. [Pure]
  27. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  28. public bool IsPrimitive()
  29. {
  30. return _type != Types.Object && _type != Types.None;
  31. }
  32. [Pure]
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. public bool IsUndefined()
  35. {
  36. return _type == Types.Undefined;
  37. }
  38. [Pure]
  39. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  40. public bool IsArray()
  41. {
  42. return this is ArrayInstance;
  43. }
  44. [Pure]
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public bool IsDate()
  47. {
  48. return this is DateInstance;
  49. }
  50. [Pure]
  51. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  52. public bool IsRegExp()
  53. {
  54. return this is RegExpInstance;
  55. }
  56. [Pure]
  57. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  58. public bool IsObject()
  59. {
  60. return _type == Types.Object;
  61. }
  62. [Pure]
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. public bool IsString()
  65. {
  66. return _type == Types.String;
  67. }
  68. [Pure]
  69. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  70. public bool IsNumber()
  71. {
  72. return _type == Types.Number;
  73. }
  74. [Pure]
  75. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  76. public bool IsBoolean()
  77. {
  78. return _type == Types.Boolean;
  79. }
  80. [Pure]
  81. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  82. public bool IsNull()
  83. {
  84. return _type == Types.Null;
  85. }
  86. [Pure]
  87. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  88. public bool IsCompletion()
  89. {
  90. return _type == Types.Completion;
  91. }
  92. [Pure]
  93. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  94. public bool IsSymbol()
  95. {
  96. return _type == Types.Symbol;
  97. }
  98. [Pure]
  99. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  100. public ObjectInstance AsObject()
  101. {
  102. if (!IsObject())
  103. {
  104. ExceptionHelper.ThrowArgumentException("The value is not an object");
  105. }
  106. return this as ObjectInstance;
  107. }
  108. [Pure]
  109. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  110. public TInstance AsInstance<TInstance>() where TInstance : class
  111. {
  112. if (!IsObject())
  113. {
  114. ExceptionHelper.ThrowArgumentException("The value is not an object");
  115. }
  116. return this as TInstance;
  117. }
  118. [Pure]
  119. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  120. public ArrayInstance AsArray()
  121. {
  122. if (!IsArray())
  123. {
  124. ExceptionHelper.ThrowArgumentException("The value is not an array");
  125. }
  126. return this as ArrayInstance;
  127. }
  128. [Pure]
  129. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  130. public DateInstance AsDate()
  131. {
  132. if (!IsDate())
  133. {
  134. ExceptionHelper.ThrowArgumentException("The value is not a date");
  135. }
  136. return this as DateInstance;
  137. }
  138. [Pure]
  139. public RegExpInstance AsRegExp()
  140. {
  141. if (!IsRegExp())
  142. {
  143. ExceptionHelper.ThrowArgumentException("The value is not a regex");
  144. }
  145. return this as RegExpInstance;
  146. }
  147. [Pure]
  148. public Completion AsCompletion()
  149. {
  150. if (_type != Types.Completion)
  151. {
  152. ExceptionHelper.ThrowArgumentException("The value is not a completion record");
  153. }
  154. // TODO not implemented
  155. return new Completion(CompletionType.Normal, Native.Undefined.Instance, null);
  156. }
  157. [Pure]
  158. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  159. public T TryCast<T>(Action<JsValue> fail = null) where T : class
  160. {
  161. if (_type == Types.Object)
  162. {
  163. if (this is T o)
  164. {
  165. return o;
  166. }
  167. }
  168. fail?.Invoke(this);
  169. return null;
  170. }
  171. [Pure]
  172. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  173. public bool Is<T>()
  174. {
  175. return IsObject() && this is T;
  176. }
  177. [Pure]
  178. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  179. public T As<T>() where T : ObjectInstance
  180. {
  181. if (IsObject())
  182. {
  183. return this as T;
  184. }
  185. return null;
  186. }
  187. // ReSharper disable once ConvertToAutoPropertyWhenPossible // PERF
  188. public Types Type
  189. {
  190. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  191. get { return _type; }
  192. }
  193. /// <summary>
  194. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  195. /// </summary>
  196. /// <param name="engine"></param>
  197. /// <param name="value"></param>
  198. /// <returns></returns>
  199. public static JsValue FromObject(Engine engine, object value)
  200. {
  201. if (value == null)
  202. {
  203. return Null;
  204. }
  205. if (value is JsValue jsValue)
  206. {
  207. return jsValue;
  208. }
  209. var converters = engine.Options._ObjectConverters;
  210. var convertersCount = converters.Count;
  211. for (var i = 0; i < convertersCount; i++)
  212. {
  213. var converter = converters[i];
  214. if (converter.TryConvert(value, out var result))
  215. {
  216. return result;
  217. }
  218. }
  219. var valueType = value.GetType();
  220. var typeMappers = Engine.TypeMappers;
  221. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  222. {
  223. return typeMapper(engine, value);
  224. }
  225. var type = value as Type;
  226. if (type != null)
  227. {
  228. var typeReference = TypeReference.CreateTypeReference(engine, type);
  229. return typeReference;
  230. }
  231. if (value is System.Array a)
  232. {
  233. // racy, we don't care, worst case we'll catch up later
  234. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  235. {
  236. [valueType] = Convert
  237. }, typeMappers);
  238. return Convert(engine, a);
  239. }
  240. if (value is Delegate d)
  241. {
  242. return new DelegateWrapper(engine, d);
  243. }
  244. if (value.GetType().IsEnum)
  245. {
  246. return JsNumber.Create((int) value);
  247. }
  248. // if no known type could be guessed, wrap it as an ObjectInstance
  249. return new ObjectWrapper(engine, value);
  250. }
  251. private static JsValue Convert(Engine e, object v)
  252. {
  253. var array = (System.Array) v;
  254. var arrayLength = (uint) array.Length;
  255. var jsArray = new ArrayInstance(e, arrayLength);
  256. jsArray.Prototype = e.Array.PrototypeObject;
  257. jsArray.Extensible = true;
  258. for (uint i = 0; i < arrayLength; ++i)
  259. {
  260. var jsItem = FromObject(e, array.GetValue(i));
  261. jsArray.WriteArrayValue(i, new PropertyDescriptor(jsItem, PropertyFlag.ConfigurableEnumerableWritable));
  262. }
  263. jsArray.SetOwnProperty("length", new PropertyDescriptor(arrayLength, PropertyFlag.OnlyWritable));
  264. return jsArray;
  265. }
  266. /// <summary>
  267. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  268. /// </summary>
  269. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  270. public abstract object ToObject();
  271. /// <summary>
  272. /// Invoke the current value as function.
  273. /// </summary>
  274. /// <param name="arguments">The arguments of the function call.</param>
  275. /// <returns>The value returned by the function call.</returns>
  276. public JsValue Invoke(params JsValue[] arguments)
  277. {
  278. return Invoke(Undefined, arguments);
  279. }
  280. /// <summary>
  281. /// Invoke the current value as function.
  282. /// </summary>
  283. /// <param name="thisObj">The this value inside the function call.</param>
  284. /// <param name="arguments">The arguments of the function call.</param>
  285. /// <returns>The value returned by the function call.</returns>
  286. public JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  287. {
  288. var callable = this as ICallable ?? ExceptionHelper.ThrowArgumentException<ICallable>("Can only invoke functions");
  289. return callable.Call(thisObj, arguments);
  290. }
  291. public static bool ReturnOnAbruptCompletion(ref JsValue argument)
  292. {
  293. if (!argument.IsCompletion())
  294. {
  295. return false;
  296. }
  297. var completion = argument.AsCompletion();
  298. if (completion.IsAbrupt())
  299. {
  300. return true;
  301. }
  302. argument = completion.Value;
  303. return false;
  304. }
  305. public override string ToString()
  306. {
  307. return "None";
  308. }
  309. public static bool operator ==(JsValue a, JsValue b)
  310. {
  311. if ((object)a == null)
  312. {
  313. if ((object)b == null)
  314. {
  315. return true;
  316. }
  317. return false;
  318. }
  319. if ((object)b == null)
  320. {
  321. return false;
  322. }
  323. return a.Equals(b);
  324. }
  325. public static bool operator !=(JsValue a, JsValue b)
  326. {
  327. if ((object)a == null)
  328. {
  329. if ((object)b == null)
  330. {
  331. return false;
  332. }
  333. return true;
  334. }
  335. if ((object)b == null)
  336. {
  337. return true;
  338. }
  339. return !a.Equals(b);
  340. }
  341. static public implicit operator JsValue(char value)
  342. {
  343. return JsString.Create(value);
  344. }
  345. static public implicit operator JsValue(int value)
  346. {
  347. return JsNumber.Create(value);
  348. }
  349. static public implicit operator JsValue(uint value)
  350. {
  351. return JsNumber.Create(value);
  352. }
  353. static public implicit operator JsValue(double value)
  354. {
  355. return JsNumber.Create(value);
  356. }
  357. public static implicit operator JsValue(bool value)
  358. {
  359. return value ? JsBoolean.True : JsBoolean.False;
  360. }
  361. public static implicit operator JsValue(string value)
  362. {
  363. if (value == null)
  364. {
  365. return Null;
  366. }
  367. return JsString.Create(value);
  368. }
  369. public override bool Equals(object obj)
  370. {
  371. if (ReferenceEquals(null, obj))
  372. {
  373. return false;
  374. }
  375. if (ReferenceEquals(this, obj))
  376. {
  377. return true;
  378. }
  379. return obj is JsValue value && Equals(value);
  380. }
  381. public abstract bool Equals(JsValue other);
  382. public override int GetHashCode()
  383. {
  384. return _type.GetHashCode();
  385. }
  386. internal class JsValueDebugView
  387. {
  388. public string Value;
  389. public JsValueDebugView(JsValue value)
  390. {
  391. switch (value.Type)
  392. {
  393. case Types.None:
  394. Value = "None";
  395. break;
  396. case Types.Undefined:
  397. Value = "undefined";
  398. break;
  399. case Types.Null:
  400. Value = "null";
  401. break;
  402. case Types.Boolean:
  403. Value = ((JsBoolean) value)._value + " (bool)";
  404. break;
  405. case Types.String:
  406. Value = value.AsStringWithoutTypeCheck() + " (string)";
  407. break;
  408. case Types.Number:
  409. Value = ((JsNumber) value)._value + " (number)";
  410. break;
  411. case Types.Object:
  412. Value = value.AsObject().GetType().Name;
  413. break;
  414. case Types.Symbol:
  415. Value = value.AsSymbol() + " (symbol)";
  416. break;
  417. default:
  418. Value = "Unknown";
  419. break;
  420. }
  421. }
  422. }
  423. }
  424. }