JsValue.cs 16 KB

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