JsValue.cs 19 KB

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