JsValue.cs 15 KB

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