JsValue.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. internal static JsValue ConvertAwaitableToPromise(Engine engine, object obj)
  105. {
  106. if (obj is Task task)
  107. {
  108. return ConvertTaskToPromise(engine, task);
  109. }
  110. #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
  111. if (obj is ValueTask valueTask)
  112. {
  113. return ConvertTaskToPromise(engine, valueTask.AsTask());
  114. }
  115. // ValueTask<T>
  116. var asTask = obj.GetType().GetMethod(nameof(ValueTask<object>.AsTask));
  117. if (asTask is not null)
  118. {
  119. return ConvertTaskToPromise(engine, (Task) asTask.Invoke(obj, parameters: null)!);
  120. }
  121. #endif
  122. return FromObject(engine, JsValue.Undefined);
  123. }
  124. internal static JsValue ConvertTaskToPromise(Engine engine, Task task)
  125. {
  126. var (promise, resolve, reject) = engine.RegisterPromise();
  127. task = task.ContinueWith(continuationAction =>
  128. {
  129. if (continuationAction.IsFaulted)
  130. {
  131. reject(FromObject(engine, continuationAction.Exception));
  132. }
  133. else if (continuationAction.IsCanceled)
  134. {
  135. reject(FromObject(engine, new ExecutionCanceledException()));
  136. }
  137. else
  138. {
  139. // Special case: Marshal `async Task` as undefined, as this is `Task<VoidTaskResult>` at runtime
  140. // See https://github.com/sebastienros/jint/pull/1567#issuecomment-1681987702
  141. if (Task.CompletedTask.Equals(continuationAction))
  142. {
  143. resolve(FromObject(engine, JsValue.Undefined));
  144. return;
  145. }
  146. var result = continuationAction.GetType().GetProperty(nameof(Task<object>.Result));
  147. if (result is not null)
  148. {
  149. resolve(FromObject(engine, result.GetValue(continuationAction)));
  150. }
  151. else
  152. {
  153. resolve(FromObject(engine, JsValue.Undefined));
  154. }
  155. }
  156. });
  157. return promise;
  158. }
  159. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  160. public Types Type
  161. {
  162. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  163. get => _type == InternalTypes.Integer
  164. ? Types.Number
  165. : (Types) (_type & ~InternalTypes.InternalFlags);
  166. }
  167. /// <summary>
  168. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  169. /// </summary>
  170. public static JsValue FromObject(Engine engine, object? value)
  171. {
  172. return FromObjectWithType(engine, value, null);
  173. }
  174. /// <summary>
  175. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance, with a type
  176. /// </summary>
  177. public static JsValue FromObjectWithType(Engine engine, object? value, Type? type)
  178. {
  179. if (value is null)
  180. {
  181. return Null;
  182. }
  183. if (value is JsValue jsValue)
  184. {
  185. return jsValue;
  186. }
  187. if (engine._objectConverters != null)
  188. {
  189. foreach (var converter in engine._objectConverters)
  190. {
  191. if (converter.TryConvert(engine, value, out var result))
  192. {
  193. return result;
  194. }
  195. }
  196. }
  197. if (DefaultObjectConverter.TryConvert(engine, value, type, out var defaultConversion))
  198. {
  199. return defaultConversion;
  200. }
  201. return null!;
  202. }
  203. /// <summary>
  204. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  205. /// </summary>
  206. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  207. public abstract object? ToObject();
  208. /// <summary>
  209. /// Coerces boolean value from <see cref="JsValue"/> instance.
  210. /// </summary>
  211. internal virtual bool ToBoolean() => _type > InternalTypes.Null;
  212. /// <summary>
  213. /// https://tc39.es/ecma262/#sec-getv
  214. /// </summary>
  215. internal JsValue GetV(Realm realm, JsValue property)
  216. {
  217. var o = TypeConverter.ToObject(realm, this);
  218. return o.Get(property, this);
  219. }
  220. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  221. public JsValue Get(JsValue property)
  222. {
  223. return Get(property, this);
  224. }
  225. /// <summary>
  226. /// https://tc39.es/ecma262/#sec-get-o-p
  227. /// </summary>
  228. public virtual JsValue Get(JsValue property, JsValue receiver)
  229. {
  230. return Undefined;
  231. }
  232. /// <summary>
  233. /// https://tc39.es/ecma262/#sec-set-o-p-v-throw
  234. /// </summary>
  235. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  236. {
  237. ExceptionHelper.ThrowNotSupportedException();
  238. return false;
  239. }
  240. /// <summary>
  241. /// https://tc39.es/ecma262/#sec-instanceofoperator
  242. /// </summary>
  243. internal bool InstanceofOperator(JsValue target)
  244. {
  245. if (target is not ObjectInstance oi)
  246. {
  247. ExceptionHelper.ThrowTypeErrorNoEngine("Right-hand side of 'instanceof' is not an object");
  248. return false;
  249. }
  250. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  251. if (instOfHandler is not null)
  252. {
  253. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] { this }));
  254. }
  255. if (!target.IsCallable)
  256. {
  257. ExceptionHelper.ThrowTypeErrorNoEngine("Right-hand side of 'instanceof' is not callable");
  258. }
  259. return target.OrdinaryHasInstance(this);
  260. }
  261. public override string ToString()
  262. {
  263. return "None";
  264. }
  265. public static bool operator ==(JsValue? a, JsValue? b)
  266. {
  267. if (a is null)
  268. {
  269. return b is null;
  270. }
  271. return b is not null && a.Equals(b);
  272. }
  273. public static bool operator !=(JsValue? a, JsValue? b)
  274. {
  275. return !(a == b);
  276. }
  277. public static implicit operator JsValue(char value)
  278. {
  279. return JsString.Create(value);
  280. }
  281. public static implicit operator JsValue(int value)
  282. {
  283. return JsNumber.Create(value);
  284. }
  285. public static implicit operator JsValue(uint value)
  286. {
  287. return JsNumber.Create(value);
  288. }
  289. public static implicit operator JsValue(double value)
  290. {
  291. return JsNumber.Create(value);
  292. }
  293. public static implicit operator JsValue(long value)
  294. {
  295. return JsNumber.Create(value);
  296. }
  297. public static implicit operator JsValue(ulong value)
  298. {
  299. return JsNumber.Create(value);
  300. }
  301. public static implicit operator JsValue(BigInteger value)
  302. {
  303. return JsBigInt.Create(value);
  304. }
  305. public static implicit operator JsValue(bool value)
  306. {
  307. return value ? JsBoolean.True : JsBoolean.False;
  308. }
  309. [DebuggerStepThrough]
  310. public static implicit operator JsValue(string? value)
  311. {
  312. return value == null ? Null : JsString.Create(value);
  313. }
  314. /// <summary>
  315. /// https://tc39.es/ecma262/#sec-islooselyequal
  316. /// </summary>
  317. protected internal virtual bool IsLooselyEqual(JsValue value)
  318. {
  319. if (ReferenceEquals(this, value))
  320. {
  321. return true;
  322. }
  323. // TODO move to type specific IsLooselyEqual
  324. var x = this;
  325. var y = value;
  326. if (x.IsNumber() && y.IsString())
  327. {
  328. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  329. }
  330. if (x.IsString() && y.IsNumber())
  331. {
  332. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  333. }
  334. if (x.IsBoolean())
  335. {
  336. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  337. }
  338. if (y.IsBoolean())
  339. {
  340. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  341. }
  342. if (y.IsObject() && (x._type & InternalTypes.Primitive) != InternalTypes.Empty)
  343. {
  344. return x.IsLooselyEqual(TypeConverter.ToPrimitive(y));
  345. }
  346. if (x.IsObject() && (y._type & InternalTypes.Primitive) != InternalTypes.Empty)
  347. {
  348. return y.IsLooselyEqual(TypeConverter.ToPrimitive(x));
  349. }
  350. return false;
  351. }
  352. /// <summary>
  353. /// Strict equality.
  354. /// </summary>
  355. public override bool Equals(object? obj) => Equals(obj as JsValue);
  356. /// <summary>
  357. /// Strict equality.
  358. /// </summary>
  359. public virtual bool Equals(JsValue? other) => ReferenceEquals(this, other);
  360. public override int GetHashCode() => _type.GetHashCode();
  361. /// <summary>
  362. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  363. /// </summary>
  364. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  365. internal JsValue Clone()
  366. {
  367. // concatenated string and arguments currently may require cloning
  368. return (_type & InternalTypes.RequiresCloning) == InternalTypes.Empty
  369. ? this
  370. : DoClone();
  371. }
  372. internal virtual JsValue DoClone() => this;
  373. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  374. internal virtual bool IsCallable => this is ICallable;
  375. /// <summary>
  376. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  377. /// </summary>
  378. internal virtual bool OrdinaryHasInstance(JsValue v)
  379. {
  380. if (!IsCallable)
  381. {
  382. return false;
  383. }
  384. var o = v as ObjectInstance;
  385. if (o is null)
  386. {
  387. return false;
  388. }
  389. var p = Get(CommonProperties.Prototype);
  390. if (p is not ObjectInstance)
  391. {
  392. ExceptionHelper.ThrowTypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  393. }
  394. while (true)
  395. {
  396. o = o.Prototype;
  397. if (o is null)
  398. {
  399. return false;
  400. }
  401. if (SameValue(p, o))
  402. {
  403. return true;
  404. }
  405. }
  406. }
  407. internal static bool SameValue(JsValue x, JsValue y)
  408. {
  409. if (ReferenceEquals(x, y))
  410. {
  411. return true;
  412. }
  413. var typea = x.Type;
  414. var typeb = y.Type;
  415. if (typea != typeb)
  416. {
  417. return false;
  418. }
  419. switch (typea)
  420. {
  421. case Types.Number:
  422. if (x._type == y._type && x._type == InternalTypes.Integer)
  423. {
  424. return x.AsInteger() == y.AsInteger();
  425. }
  426. var nx = TypeConverter.ToNumber(x);
  427. var ny = TypeConverter.ToNumber(y);
  428. if (double.IsNaN(nx) && double.IsNaN(ny))
  429. {
  430. return true;
  431. }
  432. if (nx == ny)
  433. {
  434. if (nx == 0)
  435. {
  436. // +0 !== -0
  437. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  438. }
  439. return true;
  440. }
  441. return false;
  442. case Types.String:
  443. return string.Equals(TypeConverter.ToString(x), TypeConverter.ToString(y), StringComparison.Ordinal);
  444. case Types.Boolean:
  445. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  446. case Types.Undefined:
  447. case Types.Null:
  448. return true;
  449. case Types.Symbol:
  450. return x == y;
  451. case Types.Object:
  452. return x is ObjectWrapper xo && y is ObjectWrapper yo && ReferenceEquals(xo.Target, yo.Target);
  453. default:
  454. return false;
  455. }
  456. }
  457. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  458. {
  459. if (!c.IsConstructor)
  460. {
  461. ExceptionHelper.ThrowTypeError(engine.Realm, c + " is not a constructor");
  462. }
  463. return (IConstructor) c;
  464. }
  465. }
  466. }