JsValue.cs 17 KB

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