JsValue.cs 15 KB

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