JsValue.cs 20 KB

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