JsValue.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Diagnostics.Contracts;
  4. using System.Numerics;
  5. using System.Runtime.CompilerServices;
  6. using Jint.Native.Generator;
  7. using Jint.Native.Iterator;
  8. using Jint.Native.Number;
  9. using Jint.Native.Object;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native
  14. {
  15. public abstract partial class JsValue : IEquatable<JsValue>
  16. {
  17. public static readonly JsValue Undefined = new JsUndefined();
  18. public static readonly JsValue Null = new JsNull();
  19. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  20. internal readonly InternalTypes _type;
  21. protected JsValue(Types type)
  22. {
  23. _type = (InternalTypes) type;
  24. }
  25. internal JsValue(InternalTypes type)
  26. {
  27. _type = type;
  28. }
  29. [Pure]
  30. internal virtual bool IsArray() => false;
  31. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  32. internal virtual bool IsIntegerIndexedArray => false;
  33. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  34. internal virtual bool IsConstructor => false;
  35. internal bool IsEmpty => ReferenceEquals(this, JsEmpty.Instance);
  36. [Pure]
  37. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  38. internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = GeneratorKind.Sync, ICallable? method = null)
  39. {
  40. if (!TryGetIterator(realm, out var iterator, hint, method))
  41. {
  42. ExceptionHelper.ThrowTypeError(realm, "The value is not iterable");
  43. return null!;
  44. }
  45. return iterator;
  46. }
  47. [Pure]
  48. internal IteratorInstance GetIteratorFromMethod(Realm realm, ICallable method)
  49. {
  50. var iterator = method.Call(this);
  51. if (iterator is not ObjectInstance objectInstance)
  52. {
  53. ExceptionHelper.ThrowTypeError(realm);
  54. return null!;
  55. }
  56. return new IteratorInstance.ObjectIterator(objectInstance);
  57. }
  58. [Pure]
  59. internal virtual bool TryGetIterator(
  60. Realm realm,
  61. [NotNullWhen(true)] out IteratorInstance? iterator,
  62. GeneratorKind hint = GeneratorKind.Sync,
  63. ICallable? method = null)
  64. {
  65. var obj = TypeConverter.ToObject(realm, this);
  66. if (method is null)
  67. {
  68. if (hint == GeneratorKind.Async)
  69. {
  70. method = obj.GetMethod(GlobalSymbolRegistry.AsyncIterator);
  71. if (method is null)
  72. {
  73. var syncMethod = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  74. var syncIteratorRecord = obj.GetIterator(realm, GeneratorKind.Sync, syncMethod);
  75. // TODO async CreateAsyncFromSyncIterator(syncIteratorRecord);
  76. ExceptionHelper.ThrowNotImplementedException("async");
  77. }
  78. }
  79. else
  80. {
  81. method = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  82. }
  83. }
  84. if (method is null)
  85. {
  86. iterator = null;
  87. return false;
  88. }
  89. var iteratorResult = method.Call(obj, Arguments.Empty) as ObjectInstance;
  90. if (iteratorResult is null)
  91. {
  92. ExceptionHelper.ThrowTypeError(realm, "Result of the Symbol.iterator method is not an object");
  93. }
  94. if (iteratorResult is IteratorInstance i)
  95. {
  96. iterator = i;
  97. }
  98. else
  99. {
  100. iterator = new IteratorInstance.ObjectIterator(iteratorResult);
  101. }
  102. return true;
  103. }
  104. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  105. public Types Type
  106. {
  107. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  108. get => _type == InternalTypes.Integer
  109. ? Types.Number
  110. : (Types) (_type & ~InternalTypes.InternalFlags);
  111. }
  112. /// <summary>
  113. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  114. /// </summary>
  115. public static JsValue FromObject(Engine engine, object? value)
  116. {
  117. return FromObjectWithType(engine, value, null);
  118. }
  119. /// <summary>
  120. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance, with a type
  121. /// </summary>
  122. public static JsValue FromObjectWithType(Engine engine, object? value, Type? type)
  123. {
  124. if (value is null)
  125. {
  126. return Null;
  127. }
  128. if (value is JsValue jsValue)
  129. {
  130. return jsValue;
  131. }
  132. if (engine._objectConverters != null)
  133. {
  134. foreach (var converter in engine._objectConverters)
  135. {
  136. if (converter.TryConvert(engine, value, out var result))
  137. {
  138. return result;
  139. }
  140. }
  141. }
  142. if (DefaultObjectConverter.TryConvert(engine, value, type, out var defaultConversion))
  143. {
  144. return defaultConversion;
  145. }
  146. return null!;
  147. }
  148. /// <summary>
  149. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  150. /// </summary>
  151. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  152. public abstract object? ToObject();
  153. /// <summary>
  154. /// Coerces boolean value from <see cref="JsValue"/> instance.
  155. /// </summary>
  156. internal virtual bool ToBoolean() => _type > InternalTypes.Null;
  157. /// <summary>
  158. /// https://tc39.es/ecma262/#sec-getv
  159. /// </summary>
  160. internal JsValue GetV(Realm realm, JsValue property)
  161. {
  162. var o = TypeConverter.ToObject(realm, this);
  163. return o.Get(property, this);
  164. }
  165. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  166. public JsValue Get(JsValue property)
  167. {
  168. return Get(property, this);
  169. }
  170. /// <summary>
  171. /// https://tc39.es/ecma262/#sec-get-o-p
  172. /// </summary>
  173. public virtual JsValue Get(JsValue property, JsValue receiver)
  174. {
  175. return Undefined;
  176. }
  177. /// <summary>
  178. /// https://tc39.es/ecma262/#sec-set-o-p-v-throw
  179. /// </summary>
  180. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  181. {
  182. ExceptionHelper.ThrowNotSupportedException();
  183. return false;
  184. }
  185. /// <summary>
  186. /// https://tc39.es/ecma262/#sec-instanceofoperator
  187. /// </summary>
  188. internal bool InstanceofOperator(JsValue target)
  189. {
  190. if (target is not ObjectInstance oi)
  191. {
  192. ExceptionHelper.ThrowTypeErrorNoEngine("Right-hand side of 'instanceof' is not an object");
  193. return false;
  194. }
  195. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  196. if (instOfHandler is not null)
  197. {
  198. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] { this }));
  199. }
  200. if (!target.IsCallable)
  201. {
  202. ExceptionHelper.ThrowTypeErrorNoEngine("Right-hand side of 'instanceof' is not callable");
  203. }
  204. return target.OrdinaryHasInstance(this);
  205. }
  206. public override string ToString()
  207. {
  208. return "None";
  209. }
  210. public static bool operator ==(JsValue? a, JsValue? b)
  211. {
  212. if (a is null)
  213. {
  214. return b is null;
  215. }
  216. return b is not null && a.Equals(b);
  217. }
  218. public static bool operator !=(JsValue? a, JsValue? b)
  219. {
  220. return !(a == b);
  221. }
  222. public static implicit operator JsValue(char value)
  223. {
  224. return JsString.Create(value);
  225. }
  226. public static implicit operator JsValue(int value)
  227. {
  228. return JsNumber.Create(value);
  229. }
  230. public static implicit operator JsValue(uint value)
  231. {
  232. return JsNumber.Create(value);
  233. }
  234. public static implicit operator JsValue(double value)
  235. {
  236. return JsNumber.Create(value);
  237. }
  238. public static implicit operator JsValue(long value)
  239. {
  240. return JsNumber.Create(value);
  241. }
  242. public static implicit operator JsValue(ulong value)
  243. {
  244. return JsNumber.Create(value);
  245. }
  246. public static implicit operator JsValue(BigInteger value)
  247. {
  248. return JsBigInt.Create(value);
  249. }
  250. public static implicit operator JsValue(bool value)
  251. {
  252. return value ? JsBoolean.True : JsBoolean.False;
  253. }
  254. [DebuggerStepThrough]
  255. public static implicit operator JsValue(string? value)
  256. {
  257. return value == null ? Null : JsString.Create(value);
  258. }
  259. /// <summary>
  260. /// https://tc39.es/ecma262/#sec-islooselyequal
  261. /// </summary>
  262. protected internal virtual bool IsLooselyEqual(JsValue value)
  263. {
  264. if (ReferenceEquals(this, value))
  265. {
  266. return true;
  267. }
  268. // TODO move to type specific IsLooselyEqual
  269. var x = this;
  270. var y = value;
  271. if (x.IsNumber() && y.IsString())
  272. {
  273. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  274. }
  275. if (x.IsString() && y.IsNumber())
  276. {
  277. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  278. }
  279. if (x.IsBoolean())
  280. {
  281. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  282. }
  283. if (y.IsBoolean())
  284. {
  285. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  286. }
  287. if (y.IsObject() && (x._type & InternalTypes.Primitive) != InternalTypes.Empty)
  288. {
  289. return x.IsLooselyEqual(TypeConverter.ToPrimitive(y));
  290. }
  291. if (x.IsObject() && (y._type & InternalTypes.Primitive) != InternalTypes.Empty)
  292. {
  293. return y.IsLooselyEqual(TypeConverter.ToPrimitive(x));
  294. }
  295. return false;
  296. }
  297. /// <summary>
  298. /// Strict equality.
  299. /// </summary>
  300. public override bool Equals(object? obj) => Equals(obj as JsValue);
  301. /// <summary>
  302. /// Strict equality.
  303. /// </summary>
  304. public virtual bool Equals(JsValue? other) => ReferenceEquals(this, other);
  305. public override int GetHashCode() => _type.GetHashCode();
  306. /// <summary>
  307. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  308. /// </summary>
  309. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  310. internal JsValue Clone()
  311. {
  312. // concatenated string and arguments currently may require cloning
  313. return (_type & InternalTypes.RequiresCloning) == InternalTypes.Empty
  314. ? this
  315. : DoClone();
  316. }
  317. internal virtual JsValue DoClone() => this;
  318. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  319. internal virtual bool IsCallable => this is ICallable;
  320. /// <summary>
  321. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  322. /// </summary>
  323. internal virtual bool OrdinaryHasInstance(JsValue v)
  324. {
  325. if (!IsCallable)
  326. {
  327. return false;
  328. }
  329. var o = v as ObjectInstance;
  330. if (o is null)
  331. {
  332. return false;
  333. }
  334. var p = Get(CommonProperties.Prototype);
  335. if (p is not ObjectInstance)
  336. {
  337. ExceptionHelper.ThrowTypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  338. }
  339. while (true)
  340. {
  341. o = o.Prototype;
  342. if (o is null)
  343. {
  344. return false;
  345. }
  346. if (SameValue(p, o))
  347. {
  348. return true;
  349. }
  350. }
  351. }
  352. internal static bool SameValue(JsValue x, JsValue y)
  353. {
  354. if (ReferenceEquals(x, y))
  355. {
  356. return true;
  357. }
  358. var typea = x.Type;
  359. var typeb = y.Type;
  360. if (typea != typeb)
  361. {
  362. return false;
  363. }
  364. switch (typea)
  365. {
  366. case Types.Number:
  367. if (x._type == y._type && x._type == InternalTypes.Integer)
  368. {
  369. return x.AsInteger() == y.AsInteger();
  370. }
  371. var nx = TypeConverter.ToNumber(x);
  372. var ny = TypeConverter.ToNumber(y);
  373. if (double.IsNaN(nx) && double.IsNaN(ny))
  374. {
  375. return true;
  376. }
  377. if (nx == ny)
  378. {
  379. if (nx == 0)
  380. {
  381. // +0 !== -0
  382. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  383. }
  384. return true;
  385. }
  386. return false;
  387. case Types.String:
  388. return string.Equals(TypeConverter.ToString(x), TypeConverter.ToString(y), StringComparison.Ordinal);
  389. case Types.Boolean:
  390. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  391. case Types.Undefined:
  392. case Types.Null:
  393. return true;
  394. case Types.Symbol:
  395. return x == y;
  396. case Types.Object:
  397. return x is ObjectWrapper xo && y is ObjectWrapper yo && ReferenceEquals(xo.Target, yo.Target);
  398. default:
  399. return false;
  400. }
  401. }
  402. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  403. {
  404. if (!c.IsConstructor)
  405. {
  406. ExceptionHelper.ThrowTypeError(engine.Realm, c + " is not a constructor");
  407. }
  408. return (IConstructor) c;
  409. }
  410. }
  411. }