JsValue.cs 15 KB

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