JsValue.cs 15 KB

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