JsValue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. 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(engine, 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. if (value is System.Array a)
  267. {
  268. // racy, we don't care, worst case we'll catch up later
  269. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  270. {
  271. [valueType] = Convert
  272. }, typeMappers);
  273. return Convert(engine, a);
  274. }
  275. if (value is Delegate d)
  276. {
  277. return new DelegateWrapper(engine, d);
  278. }
  279. Type t = value.GetType();
  280. if (t.IsEnum)
  281. {
  282. Type ut = Enum.GetUnderlyingType(t);
  283. if (ut == typeof(ulong))
  284. return JsNumber.Create(System.Convert.ToDouble(value));
  285. if (ut == typeof(uint) || ut == typeof(long))
  286. return JsNumber.Create(System.Convert.ToInt64(value));
  287. return JsNumber.Create(System.Convert.ToInt32(value));
  288. }
  289. // if no known type could be guessed, wrap it as an ObjectInstance
  290. var h = engine.Options._WrapObjectHandler;
  291. var o = h?.Invoke(engine, value) ?? new ObjectWrapper(engine, value);
  292. return o;
  293. }
  294. private static JsValue Convert(Engine e, object v)
  295. {
  296. var array = (System.Array) v;
  297. var arrayLength = (uint) array.Length;
  298. var jsArray = new ArrayInstance(e, arrayLength);
  299. jsArray._prototype = e.Array.PrototypeObject;
  300. for (uint i = 0; i < arrayLength; ++i)
  301. {
  302. var jsItem = FromObject(e, array.GetValue(i));
  303. jsArray.WriteArrayValue(i, new PropertyDescriptor(jsItem, PropertyFlag.ConfigurableEnumerableWritable));
  304. }
  305. jsArray.SetOwnProperty(CommonProperties.Length, new PropertyDescriptor(arrayLength, PropertyFlag.OnlyWritable));
  306. return jsArray;
  307. }
  308. /// <summary>
  309. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  310. /// </summary>
  311. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  312. public abstract object ToObject();
  313. /// <summary>
  314. /// Invoke the current value as function.
  315. /// </summary>
  316. /// <param name="arguments">The arguments of the function call.</param>
  317. /// <returns>The value returned by the function call.</returns>
  318. public JsValue Invoke(params JsValue[] arguments)
  319. {
  320. var callable = this as ICallable ?? ExceptionHelper.ThrowTypeErrorNoEngine<ICallable>("Can only invoke functions");
  321. return callable.Call(Undefined, arguments);
  322. }
  323. public virtual bool HasOwnProperty(JsValue property) => false;
  324. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  325. public JsValue Get(JsValue property)
  326. {
  327. return Get(property, this);
  328. }
  329. /// <summary>
  330. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  331. /// </summary>
  332. public virtual JsValue Get(JsValue property, JsValue receiver)
  333. {
  334. return Undefined;
  335. }
  336. /// <summary>
  337. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  338. /// </summary>
  339. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  340. {
  341. return ExceptionHelper.ThrowNotSupportedException<bool>();
  342. }
  343. /// <summary>
  344. /// https://tc39.es/ecma262/#sec-instanceofoperator
  345. /// </summary>
  346. internal bool InstanceofOperator(JsValue target)
  347. {
  348. if (target is not ObjectInstance oi)
  349. {
  350. return ExceptionHelper.ThrowTypeErrorNoEngine<bool>("not an object");
  351. }
  352. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  353. if (instOfHandler is not null)
  354. {
  355. return TypeConverter.ToBoolean(instOfHandler.Call(target, new [] { this }));
  356. }
  357. if (!target.IsCallable)
  358. {
  359. return ExceptionHelper.ThrowTypeErrorNoEngine<bool>("not callable");
  360. }
  361. return target.OrdinaryHasInstance(this);
  362. }
  363. public override string ToString()
  364. {
  365. return "None";
  366. }
  367. public static bool operator ==(JsValue a, JsValue b)
  368. {
  369. if ((object) a == null)
  370. {
  371. return (object) b == null;
  372. }
  373. return (object) b != null && a.Equals(b);
  374. }
  375. public static bool operator !=(JsValue a, JsValue b)
  376. {
  377. if ((object) a == null)
  378. {
  379. if ((object) b == null)
  380. {
  381. return false;
  382. }
  383. return true;
  384. }
  385. if ((object) b == null)
  386. {
  387. return true;
  388. }
  389. return !a.Equals(b);
  390. }
  391. public static implicit operator JsValue(char value)
  392. {
  393. return JsString.Create(value);
  394. }
  395. public static implicit operator JsValue(int value)
  396. {
  397. return JsNumber.Create(value);
  398. }
  399. public static implicit operator JsValue(uint value)
  400. {
  401. return JsNumber.Create(value);
  402. }
  403. public static implicit operator JsValue(double value)
  404. {
  405. return JsNumber.Create(value);
  406. }
  407. public static implicit operator JsValue(long value)
  408. {
  409. return JsNumber.Create(value);
  410. }
  411. public static implicit operator JsValue(ulong value)
  412. {
  413. return JsNumber.Create(value);
  414. }
  415. public static implicit operator JsValue(bool value)
  416. {
  417. return value ? JsBoolean.True : JsBoolean.False;
  418. }
  419. [DebuggerStepThrough]
  420. public static implicit operator JsValue(string value)
  421. {
  422. if (value == null)
  423. {
  424. return Null;
  425. }
  426. return JsString.Create(value);
  427. }
  428. public override bool Equals(object obj)
  429. {
  430. if (ReferenceEquals(null, obj))
  431. {
  432. return false;
  433. }
  434. if (ReferenceEquals(this, obj))
  435. {
  436. return true;
  437. }
  438. return obj is JsValue value && Equals(value);
  439. }
  440. public abstract bool Equals(JsValue other);
  441. public override int GetHashCode()
  442. {
  443. return _type.GetHashCode();
  444. }
  445. internal class JsValueDebugView
  446. {
  447. public string Value;
  448. public JsValueDebugView(JsValue value)
  449. {
  450. switch (value.Type)
  451. {
  452. case Types.None:
  453. Value = "None";
  454. break;
  455. case Types.Undefined:
  456. Value = "undefined";
  457. break;
  458. case Types.Null:
  459. Value = "null";
  460. break;
  461. case Types.Boolean:
  462. Value = ((JsBoolean) value)._value + " (bool)";
  463. break;
  464. case Types.String:
  465. Value = value.ToString() + " (string)";
  466. break;
  467. case Types.Number:
  468. Value = ((JsNumber) value)._value + " (number)";
  469. break;
  470. case Types.Object:
  471. Value = value.AsObject().GetType().Name;
  472. break;
  473. case Types.Symbol:
  474. var jsValue = ((JsSymbol) value)._value;
  475. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  476. break;
  477. default:
  478. Value = "Unknown";
  479. break;
  480. }
  481. }
  482. }
  483. /// <summary>
  484. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  485. /// </summary>
  486. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  487. internal JsValue Clone()
  488. {
  489. // concatenated string and arguments currently may require cloning
  490. return (_type & InternalTypes.RequiresCloning) == 0
  491. ? this
  492. : DoClone();
  493. }
  494. internal virtual JsValue DoClone()
  495. {
  496. return this;
  497. }
  498. internal virtual bool IsCallable => this is ICallable;
  499. /// <summary>
  500. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  501. /// </summary>
  502. internal virtual bool OrdinaryHasInstance(JsValue v)
  503. {
  504. if (!IsCallable)
  505. {
  506. return false;
  507. }
  508. if (v is not ObjectInstance o)
  509. {
  510. return false;
  511. }
  512. var p = Get(CommonProperties.Prototype);
  513. if (p is not ObjectInstance)
  514. {
  515. ExceptionHelper.ThrowTypeError(o.Engine, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  516. }
  517. while (true)
  518. {
  519. o = o.Prototype;
  520. if (o is null)
  521. {
  522. return false;
  523. }
  524. if (SameValue(p, o))
  525. {
  526. return true;
  527. }
  528. }
  529. }
  530. internal static bool SameValue(JsValue x, JsValue y)
  531. {
  532. var typea = x.Type;
  533. var typeb = y.Type;
  534. if (typea != typeb)
  535. {
  536. return false;
  537. }
  538. switch (typea)
  539. {
  540. case Types.Number:
  541. if (x._type == y._type && x._type == InternalTypes.Integer)
  542. {
  543. return x.AsInteger() == y.AsInteger();
  544. }
  545. var nx = TypeConverter.ToNumber(x);
  546. var ny = TypeConverter.ToNumber(y);
  547. if (double.IsNaN(nx) && double.IsNaN(ny))
  548. {
  549. return true;
  550. }
  551. if (nx == ny)
  552. {
  553. if (nx == 0)
  554. {
  555. // +0 !== -0
  556. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  557. }
  558. return true;
  559. }
  560. return false;
  561. case Types.String:
  562. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  563. case Types.Boolean:
  564. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  565. case Types.Undefined:
  566. case Types.Null:
  567. return true;
  568. case Types.Symbol:
  569. return x == y;
  570. default:
  571. return ReferenceEquals(x, y);
  572. }
  573. }
  574. }
  575. }