JsValue.cs 15 KB

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