JsValue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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.ObjectWrapper(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. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  355. public JsValue Get(JsValue property)
  356. {
  357. return Get(property, this);
  358. }
  359. /// <summary>
  360. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  361. /// </summary>
  362. public virtual JsValue Get(JsValue property, JsValue receiver)
  363. {
  364. return Undefined;
  365. }
  366. /// <summary>
  367. /// http://www.ecma-international.org/ecma-262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  368. /// </summary>
  369. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  370. {
  371. return ExceptionHelper.ThrowNotSupportedException<bool>();
  372. }
  373. public override string ToString()
  374. {
  375. return "None";
  376. }
  377. public static bool operator ==(JsValue a, JsValue b)
  378. {
  379. if ((object) a == null)
  380. {
  381. return (object) b == null;
  382. }
  383. return (object) b != null && a.Equals(b);
  384. }
  385. public static bool operator !=(JsValue a, JsValue b)
  386. {
  387. if ((object)a == null)
  388. {
  389. if ((object)b == null)
  390. {
  391. return false;
  392. }
  393. return true;
  394. }
  395. if ((object)b == null)
  396. {
  397. return true;
  398. }
  399. return !a.Equals(b);
  400. }
  401. public static implicit operator JsValue(char value)
  402. {
  403. return JsString.Create(value);
  404. }
  405. public static implicit operator JsValue(int value)
  406. {
  407. return JsNumber.Create(value);
  408. }
  409. public static implicit operator JsValue(uint value)
  410. {
  411. return JsNumber.Create(value);
  412. }
  413. public static implicit operator JsValue(double value)
  414. {
  415. return JsNumber.Create(value);
  416. }
  417. public static implicit operator JsValue(long value)
  418. {
  419. return JsNumber.Create(value);
  420. }
  421. public static implicit operator JsValue(ulong value)
  422. {
  423. return JsNumber.Create(value);
  424. }
  425. public static implicit operator JsValue(bool value)
  426. {
  427. return value ? JsBoolean.True : JsBoolean.False;
  428. }
  429. [DebuggerStepThrough]
  430. public static implicit operator JsValue(string value)
  431. {
  432. if (value == null)
  433. {
  434. return Null;
  435. }
  436. return JsString.Create(value);
  437. }
  438. public override bool Equals(object obj)
  439. {
  440. if (ReferenceEquals(null, obj))
  441. {
  442. return false;
  443. }
  444. if (ReferenceEquals(this, obj))
  445. {
  446. return true;
  447. }
  448. return obj is JsValue value && Equals(value);
  449. }
  450. public abstract bool Equals(JsValue other);
  451. public override int GetHashCode()
  452. {
  453. return _type.GetHashCode();
  454. }
  455. internal class JsValueDebugView
  456. {
  457. public string Value;
  458. public JsValueDebugView(JsValue value)
  459. {
  460. switch (value.Type)
  461. {
  462. case Types.None:
  463. Value = "None";
  464. break;
  465. case Types.Undefined:
  466. Value = "undefined";
  467. break;
  468. case Types.Null:
  469. Value = "null";
  470. break;
  471. case Types.Boolean:
  472. Value = ((JsBoolean) value)._value + " (bool)";
  473. break;
  474. case Types.String:
  475. Value = value.AsStringWithoutTypeCheck() + " (string)";
  476. break;
  477. case Types.Number:
  478. Value = ((JsNumber) value)._value + " (number)";
  479. break;
  480. case Types.Object:
  481. Value = value.AsObject().GetType().Name;
  482. break;
  483. case Types.Symbol:
  484. var jsValue = ((JsSymbol) value)._value;
  485. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  486. break;
  487. default:
  488. Value = "Unknown";
  489. break;
  490. }
  491. }
  492. }
  493. /// <summary>
  494. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  495. /// </summary>
  496. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  497. internal JsValue Clone()
  498. {
  499. // concatenated string and arguments currently may require cloning
  500. return (_type & InternalTypes.RequiresCloning) == 0
  501. ? this
  502. : DoClone();
  503. }
  504. internal virtual JsValue DoClone()
  505. {
  506. return this;
  507. }
  508. internal static bool SameValue(JsValue x, JsValue y)
  509. {
  510. var typea = x.Type;
  511. var typeb = y.Type;
  512. if (typea != typeb)
  513. {
  514. return false;
  515. }
  516. switch (typea)
  517. {
  518. case Types.Number:
  519. if (x._type == y._type && x._type == InternalTypes.Integer)
  520. {
  521. return x.AsInteger() == y.AsInteger();
  522. }
  523. var nx = TypeConverter.ToNumber(x);
  524. var ny = TypeConverter.ToNumber(y);
  525. if (double.IsNaN(nx) && double.IsNaN(ny))
  526. {
  527. return true;
  528. }
  529. if (nx == ny)
  530. {
  531. if (nx == 0)
  532. {
  533. // +0 !== -0
  534. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  535. }
  536. return true;
  537. }
  538. return false;
  539. case Types.String:
  540. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  541. case Types.Boolean:
  542. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  543. case Types.Undefined:
  544. case Types.Null:
  545. return true;
  546. case Types.Symbol:
  547. return x == y;
  548. default:
  549. return ReferenceEquals(x, y);
  550. }
  551. }
  552. }
  553. }