JsValue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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.Number;
  11. using Jint.Native.Object;
  12. using Jint.Native.RegExp;
  13. using Jint.Native.Symbol;
  14. using Jint.Runtime;
  15. using Jint.Runtime.Descriptors;
  16. using Jint.Runtime.Interop;
  17. namespace Jint.Native
  18. {
  19. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  20. public abstract class JsValue : IEquatable<JsValue>
  21. {
  22. public static readonly JsValue Undefined = new JsUndefined();
  23. public static readonly JsValue Null = new JsNull();
  24. internal readonly InternalTypes _type;
  25. protected JsValue(Types type)
  26. {
  27. _type = (InternalTypes) type;
  28. }
  29. internal JsValue(InternalTypes type)
  30. {
  31. _type = type;
  32. }
  33. [Pure]
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public bool IsPrimitive()
  36. {
  37. return (_type & (InternalTypes.Primitive | InternalTypes.Undefined | InternalTypes.Null)) != 0;
  38. }
  39. [Pure]
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public bool IsUndefined()
  42. {
  43. return _type == InternalTypes.Undefined;
  44. }
  45. [Pure]
  46. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  47. internal bool IsNullOrUndefined()
  48. {
  49. return _type < InternalTypes.Boolean;
  50. }
  51. [Pure]
  52. public virtual bool IsArray()
  53. {
  54. return this is ArrayInstance;
  55. }
  56. [Pure]
  57. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  58. public bool IsDate()
  59. {
  60. return this is DateInstance;
  61. }
  62. [Pure]
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. public bool IsRegExp()
  65. {
  66. if (!(this is ObjectInstance oi))
  67. {
  68. return false;
  69. }
  70. var matcher = oi.Get(GlobalSymbolRegistry.Match);
  71. if (!matcher.IsUndefined())
  72. {
  73. return TypeConverter.ToBoolean(matcher);
  74. }
  75. return this is RegExpInstance;
  76. }
  77. [Pure]
  78. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  79. public bool IsObject()
  80. {
  81. return (_type & InternalTypes.Object) != 0;
  82. }
  83. [Pure]
  84. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  85. public bool IsString()
  86. {
  87. return (_type & InternalTypes.String) != 0;
  88. }
  89. [Pure]
  90. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  91. public bool IsNumber()
  92. {
  93. return (_type & (InternalTypes.Number | InternalTypes.Integer)) != 0;
  94. }
  95. [Pure]
  96. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  97. internal bool IsInteger()
  98. {
  99. return _type == InternalTypes.Integer;
  100. }
  101. [Pure]
  102. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  103. public bool IsBoolean()
  104. {
  105. return _type == InternalTypes.Boolean;
  106. }
  107. [Pure]
  108. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  109. public bool IsNull()
  110. {
  111. return _type == InternalTypes.Null;
  112. }
  113. internal virtual bool IsIntegerIndexedArray => false;
  114. [Pure]
  115. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  116. public bool IsSymbol()
  117. {
  118. return _type == InternalTypes.Symbol;
  119. }
  120. [Pure]
  121. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  122. public ObjectInstance AsObject()
  123. {
  124. if (!IsObject())
  125. {
  126. ExceptionHelper.ThrowArgumentException("The value is not an object");
  127. }
  128. return this as ObjectInstance;
  129. }
  130. [Pure]
  131. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  132. public TInstance AsInstance<TInstance>() where TInstance : class
  133. {
  134. if (!IsObject())
  135. {
  136. ExceptionHelper.ThrowArgumentException("The value is not an object");
  137. }
  138. return this as TInstance;
  139. }
  140. [Pure]
  141. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  142. public ArrayInstance AsArray()
  143. {
  144. if (!IsArray())
  145. {
  146. ExceptionHelper.ThrowArgumentException("The value is not an array");
  147. }
  148. return this as ArrayInstance;
  149. }
  150. [Pure]
  151. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  152. internal IIterator GetIterator(Engine engine)
  153. {
  154. if (!TryGetIterator(engine, out var iterator))
  155. {
  156. return ExceptionHelper.ThrowTypeError<IIterator>(engine, "The value is not iterable");
  157. }
  158. return iterator;
  159. }
  160. [Pure]
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. internal bool TryGetIterator(Engine engine, out IIterator iterator)
  163. {
  164. var objectInstance = TypeConverter.ToObject(engine, this);
  165. if (!objectInstance.TryGetValue(GlobalSymbolRegistry.Iterator, out var value)
  166. || !(value is ICallable callable))
  167. {
  168. iterator = null;
  169. return false;
  170. }
  171. var obj = callable.Call(this, Arguments.Empty) as ObjectInstance
  172. ?? ExceptionHelper.ThrowTypeError<ObjectInstance>(engine, "Result of the Symbol.iterator method is not an object");
  173. if (obj is IIterator i)
  174. {
  175. iterator = i;
  176. }
  177. else
  178. {
  179. iterator = new IteratorInstance.ObjectIterator(obj);
  180. }
  181. return true;
  182. }
  183. [Pure]
  184. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  185. public DateInstance AsDate()
  186. {
  187. if (!IsDate())
  188. {
  189. ExceptionHelper.ThrowArgumentException("The value is not a date");
  190. }
  191. return this as DateInstance;
  192. }
  193. [Pure]
  194. public RegExpInstance AsRegExp()
  195. {
  196. if (!IsRegExp())
  197. {
  198. ExceptionHelper.ThrowArgumentException("The value is not a regex");
  199. }
  200. return this as RegExpInstance;
  201. }
  202. [Pure]
  203. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  204. public T TryCast<T>() where T : class
  205. {
  206. return this as T;
  207. }
  208. [Pure]
  209. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  210. public T TryCast<T>(Action<JsValue> fail) where T : class
  211. {
  212. if (this is T o)
  213. {
  214. return o;
  215. }
  216. fail.Invoke(this);
  217. return null;
  218. }
  219. [Pure]
  220. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  221. public T As<T>() where T : ObjectInstance
  222. {
  223. if (IsObject())
  224. {
  225. return this as T;
  226. }
  227. return null;
  228. }
  229. public Types Type
  230. {
  231. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  232. get => _type == InternalTypes.Integer
  233. ? Types.Number
  234. : (Types) (_type & ~InternalTypes.InternalFlags);
  235. }
  236. internal virtual bool IsConstructor => false;
  237. /// <summary>
  238. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  239. /// </summary>
  240. /// <param name="engine"></param>
  241. /// <param name="value"></param>
  242. /// <returns></returns>
  243. public static JsValue FromObject(Engine engine, object value)
  244. {
  245. if (value == null)
  246. {
  247. return Null;
  248. }
  249. if (value is JsValue jsValue)
  250. {
  251. return jsValue;
  252. }
  253. var converters = engine.Options._ObjectConverters;
  254. var convertersCount = converters.Count;
  255. for (var i = 0; i < convertersCount; i++)
  256. {
  257. var converter = converters[i];
  258. if (converter.TryConvert(engine, value, out var result))
  259. {
  260. return result;
  261. }
  262. }
  263. var valueType = value.GetType();
  264. var typeMappers = Engine.TypeMappers;
  265. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  266. {
  267. return typeMapper(engine, value);
  268. }
  269. var type = value as Type;
  270. if (type != null)
  271. {
  272. var typeReference = TypeReference.CreateTypeReference(engine, type);
  273. return typeReference;
  274. }
  275. if (value is System.Array a)
  276. {
  277. // racy, we don't care, worst case we'll catch up later
  278. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  279. {
  280. [valueType] = Convert
  281. }, typeMappers);
  282. return Convert(engine, a);
  283. }
  284. if (value is Delegate d)
  285. {
  286. return new DelegateWrapper(engine, d);
  287. }
  288. Type t = value.GetType();
  289. if (t.IsEnum)
  290. {
  291. Type ut = Enum.GetUnderlyingType(t);
  292. if (ut == typeof(ulong))
  293. return JsNumber.Create(System.Convert.ToDouble(value));
  294. if (ut == typeof(uint) || ut == typeof(long))
  295. return JsNumber.Create(System.Convert.ToInt64(value));
  296. return JsNumber.Create(System.Convert.ToInt32(value));
  297. }
  298. // if no known type could be guessed, wrap it as an ObjectInstance
  299. var h = engine.Options._WrapObjectHandler;
  300. var o = h?.Invoke(engine, value) ?? new ObjectWrapper(engine, value);
  301. return o;
  302. }
  303. private static JsValue Convert(Engine e, object v)
  304. {
  305. var array = (System.Array) v;
  306. var arrayLength = (uint) array.Length;
  307. var jsArray = new ArrayInstance(e, arrayLength);
  308. jsArray._prototype = e.Array.PrototypeObject;
  309. for (uint i = 0; i < arrayLength; ++i)
  310. {
  311. var jsItem = FromObject(e, array.GetValue(i));
  312. jsArray.WriteArrayValue(i, new PropertyDescriptor(jsItem, PropertyFlag.ConfigurableEnumerableWritable));
  313. }
  314. jsArray.SetOwnProperty(CommonProperties.Length, new PropertyDescriptor(arrayLength, PropertyFlag.OnlyWritable));
  315. return jsArray;
  316. }
  317. /// <summary>
  318. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  319. /// </summary>
  320. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  321. public abstract object ToObject();
  322. /// <summary>
  323. /// Invoke the current value as function.
  324. /// </summary>
  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(params JsValue[] arguments)
  328. {
  329. return Invoke(Undefined, arguments);
  330. }
  331. /// <summary>
  332. /// Invoke the current value as function.
  333. /// </summary>
  334. /// <param name="thisObj">The this value inside the function call.</param>
  335. /// <param name="arguments">The arguments of the function call.</param>
  336. /// <returns>The value returned by the function call.</returns>
  337. internal JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  338. {
  339. var callable = this as ICallable ?? ExceptionHelper.ThrowTypeErrorNoEngine<ICallable>("Can only invoke functions");
  340. return callable.Call(thisObj, arguments);
  341. }
  342. /// <summary>
  343. /// Invoke the given property as function.
  344. /// </summary>
  345. /// <param name="v">Serves as both the lookup point for the property and the this value of the call</param>
  346. /// <param name="propertyName">Property that should be ICallable</param>
  347. /// <param name="arguments">The arguments of the function call.</param>
  348. /// <returns>The value returned by the function call.</returns>
  349. internal static JsValue Invoke(JsValue v, JsValue propertyName, JsValue[] arguments)
  350. {
  351. var func = v.Get(propertyName);
  352. var callable = func as ICallable ?? ExceptionHelper.ThrowTypeErrorNoEngine<ICallable>("Can only invoke functions");
  353. return callable.Call(v, arguments);
  354. }
  355. public virtual bool HasOwnProperty(JsValue property) => false;
  356. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  357. public JsValue Get(JsValue property)
  358. {
  359. return Get(property, this);
  360. }
  361. /// <summary>
  362. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  363. /// </summary>
  364. public virtual JsValue Get(JsValue property, JsValue receiver)
  365. {
  366. return Undefined;
  367. }
  368. /// <summary>
  369. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  370. /// </summary>
  371. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  372. {
  373. return ExceptionHelper.ThrowNotSupportedException<bool>();
  374. }
  375. public override string ToString()
  376. {
  377. return "None";
  378. }
  379. public static bool operator ==(JsValue a, JsValue b)
  380. {
  381. if ((object) a == null)
  382. {
  383. return (object) b == null;
  384. }
  385. return (object) b != null && a.Equals(b);
  386. }
  387. public static bool operator !=(JsValue a, JsValue b)
  388. {
  389. if ((object)a == null)
  390. {
  391. if ((object)b == null)
  392. {
  393. return false;
  394. }
  395. return true;
  396. }
  397. if ((object)b == null)
  398. {
  399. return true;
  400. }
  401. return !a.Equals(b);
  402. }
  403. public static implicit operator JsValue(char value)
  404. {
  405. return JsString.Create(value);
  406. }
  407. public static implicit operator JsValue(int value)
  408. {
  409. return JsNumber.Create(value);
  410. }
  411. public static implicit operator JsValue(uint value)
  412. {
  413. return JsNumber.Create(value);
  414. }
  415. public static implicit operator JsValue(double value)
  416. {
  417. return JsNumber.Create(value);
  418. }
  419. public static implicit operator JsValue(long value)
  420. {
  421. return JsNumber.Create(value);
  422. }
  423. public static implicit operator JsValue(ulong value)
  424. {
  425. return JsNumber.Create(value);
  426. }
  427. public static implicit operator JsValue(bool value)
  428. {
  429. return value ? JsBoolean.True : JsBoolean.False;
  430. }
  431. [DebuggerStepThrough]
  432. public static implicit operator JsValue(string value)
  433. {
  434. if (value == null)
  435. {
  436. return Null;
  437. }
  438. return JsString.Create(value);
  439. }
  440. public override bool Equals(object obj)
  441. {
  442. if (ReferenceEquals(null, obj))
  443. {
  444. return false;
  445. }
  446. if (ReferenceEquals(this, obj))
  447. {
  448. return true;
  449. }
  450. return obj is JsValue value && Equals(value);
  451. }
  452. public abstract bool Equals(JsValue other);
  453. public override int GetHashCode()
  454. {
  455. return _type.GetHashCode();
  456. }
  457. internal class JsValueDebugView
  458. {
  459. public string Value;
  460. public JsValueDebugView(JsValue value)
  461. {
  462. switch (value.Type)
  463. {
  464. case Types.None:
  465. Value = "None";
  466. break;
  467. case Types.Undefined:
  468. Value = "undefined";
  469. break;
  470. case Types.Null:
  471. Value = "null";
  472. break;
  473. case Types.Boolean:
  474. Value = ((JsBoolean) value)._value + " (bool)";
  475. break;
  476. case Types.String:
  477. Value = value.ToString() + " (string)";
  478. break;
  479. case Types.Number:
  480. Value = ((JsNumber) value)._value + " (number)";
  481. break;
  482. case Types.Object:
  483. Value = value.AsObject().GetType().Name;
  484. break;
  485. case Types.Symbol:
  486. var jsValue = ((JsSymbol) value)._value;
  487. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  488. break;
  489. default:
  490. Value = "Unknown";
  491. break;
  492. }
  493. }
  494. }
  495. /// <summary>
  496. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  497. /// </summary>
  498. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  499. internal JsValue Clone()
  500. {
  501. // concatenated string and arguments currently may require cloning
  502. return (_type & InternalTypes.RequiresCloning) == 0
  503. ? this
  504. : DoClone();
  505. }
  506. internal virtual JsValue DoClone()
  507. {
  508. return this;
  509. }
  510. internal virtual bool IsCallable => this is ICallable;
  511. internal static bool SameValue(JsValue x, JsValue y)
  512. {
  513. var typea = x.Type;
  514. var typeb = y.Type;
  515. if (typea != typeb)
  516. {
  517. return false;
  518. }
  519. switch (typea)
  520. {
  521. case Types.Number:
  522. if (x._type == y._type && x._type == InternalTypes.Integer)
  523. {
  524. return x.AsInteger() == y.AsInteger();
  525. }
  526. var nx = TypeConverter.ToNumber(x);
  527. var ny = TypeConverter.ToNumber(y);
  528. if (double.IsNaN(nx) && double.IsNaN(ny))
  529. {
  530. return true;
  531. }
  532. if (nx == ny)
  533. {
  534. if (nx == 0)
  535. {
  536. // +0 !== -0
  537. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  538. }
  539. return true;
  540. }
  541. return false;
  542. case Types.String:
  543. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  544. case Types.Boolean:
  545. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  546. case Types.Undefined:
  547. case Types.Null:
  548. return true;
  549. case Types.Symbol:
  550. return x == y;
  551. default:
  552. return ReferenceEquals(x, y);
  553. }
  554. }
  555. }
  556. }