JsValue.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. using System;
  2. using System.Diagnostics;
  3. using System.Diagnostics.Contracts;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Native.Array;
  6. using Jint.Native.Date;
  7. using Jint.Native.Iterator;
  8. using Jint.Native.Number;
  9. using Jint.Native.Object;
  10. using Jint.Native.Promise;
  11. using Jint.Native.RegExp;
  12. using Jint.Native.Symbol;
  13. using Jint.Runtime;
  14. namespace Jint.Native
  15. {
  16. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  17. public abstract class JsValue : IEquatable<JsValue>
  18. {
  19. public static readonly JsValue Undefined = new JsUndefined();
  20. public static readonly JsValue Null = new JsNull();
  21. internal readonly InternalTypes _type;
  22. protected JsValue(Types type)
  23. {
  24. _type = (InternalTypes) type;
  25. }
  26. internal JsValue(InternalTypes type)
  27. {
  28. _type = type;
  29. }
  30. [Pure]
  31. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  32. public bool IsPrimitive()
  33. {
  34. return (_type & (InternalTypes.Primitive | InternalTypes.Undefined | InternalTypes.Null)) != 0;
  35. }
  36. [Pure]
  37. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  38. public bool IsUndefined()
  39. {
  40. return _type == InternalTypes.Undefined;
  41. }
  42. [Pure]
  43. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  44. internal bool IsNullOrUndefined()
  45. {
  46. return _type < InternalTypes.Boolean;
  47. }
  48. [Pure]
  49. public virtual bool IsArray() => false;
  50. [Pure]
  51. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  52. public bool IsDate()
  53. {
  54. return this is DateInstance;
  55. }
  56. [Pure]
  57. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  58. public bool IsPromise()
  59. {
  60. return this is PromiseInstance;
  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(Realm realm)
  153. {
  154. if (!TryGetIterator(realm, out var iterator))
  155. {
  156. ExceptionHelper.ThrowTypeError(realm, "The value is not iterable");
  157. }
  158. return iterator;
  159. }
  160. [Pure]
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. internal bool TryGetIterator(Realm realm, out IIterator iterator)
  163. {
  164. var objectInstance = TypeConverter.ToObject(realm, 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. if (obj is null)
  173. {
  174. ExceptionHelper.ThrowTypeError(realm, "Result of the Symbol.iterator method is not an object");
  175. }
  176. if (obj is IIterator i)
  177. {
  178. iterator = i;
  179. }
  180. else
  181. {
  182. iterator = new IteratorInstance.ObjectIterator(obj);
  183. }
  184. return true;
  185. }
  186. [Pure]
  187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. public DateInstance AsDate()
  189. {
  190. if (!IsDate())
  191. {
  192. ExceptionHelper.ThrowArgumentException("The value is not a date");
  193. }
  194. return this as DateInstance;
  195. }
  196. [Pure]
  197. public RegExpInstance AsRegExp()
  198. {
  199. if (!IsRegExp())
  200. {
  201. ExceptionHelper.ThrowArgumentException("The value is not a regex");
  202. }
  203. return this as RegExpInstance;
  204. }
  205. [Pure]
  206. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  207. public T TryCast<T>() where T : class
  208. {
  209. return this as T;
  210. }
  211. [Pure]
  212. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  213. public T TryCast<T>(Action<JsValue> fail) where T : class
  214. {
  215. if (this is T o)
  216. {
  217. return o;
  218. }
  219. fail.Invoke(this);
  220. return null;
  221. }
  222. [Pure]
  223. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  224. public T As<T>() where T : ObjectInstance
  225. {
  226. if (IsObject())
  227. {
  228. return this as T;
  229. }
  230. return null;
  231. }
  232. public Types Type
  233. {
  234. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  235. get => _type == InternalTypes.Integer
  236. ? Types.Number
  237. : (Types) (_type & ~InternalTypes.InternalFlags);
  238. }
  239. internal virtual bool IsConstructor => false;
  240. /// <summary>
  241. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  242. /// </summary>
  243. public static JsValue FromObject(Engine engine, object value)
  244. {
  245. if (value is null)
  246. {
  247. return Null;
  248. }
  249. if (value is JsValue jsValue)
  250. {
  251. return jsValue;
  252. }
  253. if (engine._objectConverters != null)
  254. {
  255. foreach (var converter in engine._objectConverters)
  256. {
  257. if (converter.TryConvert(engine, value, out var result))
  258. {
  259. return result;
  260. }
  261. }
  262. }
  263. if (DefaultObjectConverter.TryConvert(engine, value, out var defaultConversion))
  264. {
  265. return defaultConversion;
  266. }
  267. return null;
  268. }
  269. /// <summary>
  270. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  271. /// </summary>
  272. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  273. public abstract object ToObject();
  274. /// <summary>
  275. /// Invoke the current value as function.
  276. /// </summary>
  277. /// <param name="arguments">The arguments of the function call.</param>
  278. /// <returns>The value returned by the function call.</returns>
  279. public JsValue Invoke(params JsValue[] arguments)
  280. {
  281. var callable = this as ICallable;
  282. if (callable is null)
  283. {
  284. ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
  285. }
  286. return callable.Call(Undefined, arguments);
  287. }
  288. public virtual bool HasOwnProperty(JsValue property) => false;
  289. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  290. public JsValue Get(JsValue property)
  291. {
  292. return Get(property, this);
  293. }
  294. /// <summary>
  295. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  296. /// </summary>
  297. public virtual JsValue Get(JsValue property, JsValue receiver)
  298. {
  299. return Undefined;
  300. }
  301. /// <summary>
  302. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  303. /// </summary>
  304. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  305. {
  306. ExceptionHelper.ThrowNotSupportedException();
  307. return false;
  308. }
  309. /// <summary>
  310. /// https://tc39.es/ecma262/#sec-instanceofoperator
  311. /// </summary>
  312. internal bool InstanceofOperator(JsValue target)
  313. {
  314. var oi = target as ObjectInstance;
  315. if (oi is null)
  316. {
  317. ExceptionHelper.ThrowTypeErrorNoEngine("not an object");
  318. }
  319. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  320. if (instOfHandler is not null)
  321. {
  322. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] {this}));
  323. }
  324. if (!target.IsCallable)
  325. {
  326. ExceptionHelper.ThrowTypeErrorNoEngine("not callable");
  327. }
  328. return target.OrdinaryHasInstance(this);
  329. }
  330. public override string ToString()
  331. {
  332. return "None";
  333. }
  334. public static bool operator ==(JsValue a, JsValue b)
  335. {
  336. if ((object) a == null)
  337. {
  338. return (object) b == null;
  339. }
  340. return (object) b != null && a.Equals(b);
  341. }
  342. public static bool operator !=(JsValue a, JsValue b)
  343. {
  344. if ((object) a == null)
  345. {
  346. if ((object) b == null)
  347. {
  348. return false;
  349. }
  350. return true;
  351. }
  352. if ((object) b == null)
  353. {
  354. return true;
  355. }
  356. return !a.Equals(b);
  357. }
  358. public static implicit operator JsValue(char value)
  359. {
  360. return JsString.Create(value);
  361. }
  362. public static implicit operator JsValue(int value)
  363. {
  364. return JsNumber.Create(value);
  365. }
  366. public static implicit operator JsValue(uint value)
  367. {
  368. return JsNumber.Create(value);
  369. }
  370. public static implicit operator JsValue(double value)
  371. {
  372. return JsNumber.Create(value);
  373. }
  374. public static implicit operator JsValue(long value)
  375. {
  376. return JsNumber.Create(value);
  377. }
  378. public static implicit operator JsValue(ulong value)
  379. {
  380. return JsNumber.Create(value);
  381. }
  382. public static implicit operator JsValue(bool value)
  383. {
  384. return value ? JsBoolean.True : JsBoolean.False;
  385. }
  386. [DebuggerStepThrough]
  387. public static implicit operator JsValue(string value)
  388. {
  389. if (value == null)
  390. {
  391. return Null;
  392. }
  393. return JsString.Create(value);
  394. }
  395. public override bool Equals(object obj)
  396. {
  397. if (ReferenceEquals(null, obj))
  398. {
  399. return false;
  400. }
  401. if (ReferenceEquals(this, obj))
  402. {
  403. return true;
  404. }
  405. return obj is JsValue value && Equals(value);
  406. }
  407. public abstract bool Equals(JsValue other);
  408. public override int GetHashCode()
  409. {
  410. return _type.GetHashCode();
  411. }
  412. internal class JsValueDebugView
  413. {
  414. public string Value;
  415. public JsValueDebugView(JsValue value)
  416. {
  417. switch (value.Type)
  418. {
  419. case Types.None:
  420. Value = "None";
  421. break;
  422. case Types.Undefined:
  423. Value = "undefined";
  424. break;
  425. case Types.Null:
  426. Value = "null";
  427. break;
  428. case Types.Boolean:
  429. Value = ((JsBoolean) value)._value + " (bool)";
  430. break;
  431. case Types.String:
  432. Value = value.ToString() + " (string)";
  433. break;
  434. case Types.Number:
  435. Value = ((JsNumber) value)._value + " (number)";
  436. break;
  437. case Types.Object:
  438. Value = value.AsObject().GetType().Name;
  439. break;
  440. case Types.Symbol:
  441. var jsValue = ((JsSymbol) value)._value;
  442. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  443. break;
  444. default:
  445. Value = "Unknown";
  446. break;
  447. }
  448. }
  449. }
  450. /// <summary>
  451. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  452. /// </summary>
  453. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  454. internal JsValue Clone()
  455. {
  456. // concatenated string and arguments currently may require cloning
  457. return (_type & InternalTypes.RequiresCloning) == 0
  458. ? this
  459. : DoClone();
  460. }
  461. internal virtual JsValue DoClone()
  462. {
  463. return this;
  464. }
  465. internal virtual bool IsCallable => this is ICallable;
  466. /// <summary>
  467. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  468. /// </summary>
  469. internal virtual bool OrdinaryHasInstance(JsValue v)
  470. {
  471. if (!IsCallable)
  472. {
  473. return false;
  474. }
  475. if (v is not ObjectInstance o)
  476. {
  477. return false;
  478. }
  479. var p = Get(CommonProperties.Prototype);
  480. if (p is not ObjectInstance)
  481. {
  482. ExceptionHelper.ThrowTypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  483. }
  484. while (true)
  485. {
  486. o = o.Prototype;
  487. if (o is null)
  488. {
  489. return false;
  490. }
  491. if (SameValue(p, o))
  492. {
  493. return true;
  494. }
  495. }
  496. }
  497. internal static bool SameValue(JsValue x, JsValue y)
  498. {
  499. var typea = x.Type;
  500. var typeb = y.Type;
  501. if (typea != typeb)
  502. {
  503. return false;
  504. }
  505. switch (typea)
  506. {
  507. case Types.Number:
  508. if (x._type == y._type && x._type == InternalTypes.Integer)
  509. {
  510. return x.AsInteger() == y.AsInteger();
  511. }
  512. var nx = TypeConverter.ToNumber(x);
  513. var ny = TypeConverter.ToNumber(y);
  514. if (double.IsNaN(nx) && double.IsNaN(ny))
  515. {
  516. return true;
  517. }
  518. if (nx == ny)
  519. {
  520. if (nx == 0)
  521. {
  522. // +0 !== -0
  523. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  524. }
  525. return true;
  526. }
  527. return false;
  528. case Types.String:
  529. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  530. case Types.Boolean:
  531. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  532. case Types.Undefined:
  533. case Types.Null:
  534. return true;
  535. case Types.Symbol:
  536. return x == y;
  537. default:
  538. return ReferenceEquals(x, y);
  539. }
  540. }
  541. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  542. {
  543. var constructor = c as IConstructor;
  544. if (constructor is null)
  545. {
  546. ExceptionHelper.ThrowTypeError(engine.Realm, c + " is not a constructor");
  547. }
  548. return constructor;
  549. }
  550. }
  551. }