JsValue.cs 15 KB

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